Android
 Computer >> コンピューター >  >> プログラミング >> Android

AndroidでArrayListをSharedPreferencesに保存する方法は?


arraylistの例を保存するための共有設定に入る前に、Androidでの共有設定とは何かを知っておく必要があります。共有設定を使用して、値をキーと値のペアとして保存または取得できます。以下に示すように、共有設定では5つの異なる方法を使用できます-

  • Edit() −共有設定値を編集します

  • commit() −xmlファイルで共有設定値をコミットします

  • apply() −エディターから共有設定への変更をコミットバックします。

  • remove(String key) −共有設定使用キーからキーと値を削除します。

  • Put() −キーと値を共有設定xmlに配置します。

以下に示す共有設定の構文例-

final SharedPreferences sharedPreferences = getSharedPreferences("USER",MODE_PRIVATE);

上記の構文では、共有設定ファイルをUSER.xmlとして作成しました。これはプライベートモードであり、他のアプリケーションがこの共有設定にアクセスできないことを意味します。

以下の例は、Androidで共有設定を使用する方法を示しています。

ステップ1 − Android Studioで新しいプロジェクトを作成し、[ファイル]⇒[新しいプロジェクト]に移動して、新しいプロジェクトを作成するために必要なすべての詳細を入力します。

ステップ2 −次のコードを res / layout / activity_main.xmlに追加します 。

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
   xmlns:android = "https://schemas.android.com/apk/res/android"
   xmlns:app = "https://schemas.android.com/apk/res-auto"
   xmlns:tools = "https://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:orientation = "vertical"
   tools:context = ".MainActivity"
   tools:layout_editor_absoluteY = "81dp">
   <EditText
      android:id = "@+id/name"
      android:layout_width = "match_parent"
      android:layout_height = "60dp"
      android:layout_marginTop = "8dp"
      android:autofillHints = ""
      android:hint = "NAME"
      app:layout_constraintTop_toTopOf = "parent"
      tools:layout_editor_absoluteX = "0dp" />
   <EditText
      android:id = "@+id/address"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:layout_marginTop = "84dp"
      android:hint = "Phone Number"
      android:importantForAutofill = "no"
      android:inputType = ""
      app:layout_constraintTop_toTopOf = "@+id/name"
      tools:layout_editor_absoluteX = "16dp"
      tools:targetApi = "o" />
   <Button
      android:id = "@+id/button"
      android:layout_width = "108dp"
      android:layout_height = "wrap_content"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "120dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:gravity = "center_horizontal"
      android:text = "Save"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintHorizontal_bias = "0.503"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toTopOf = "@+id/address" />
   <Button
      android:id = "@+id/read"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "88dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:gravity = "center_horizontal"
      android:text = "read"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toBottomOf = "@+id/button" />
   <TextView
      android:id = "@+id/result"
      android:layout_width = "wrap_content"
      android:layout_height = "0dp"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "184dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:text = "result"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toBottomOf = "@+id/button" />
</android.support.constraint.ConstraintLayout>

上記のxmlには、名前と住所の2つの編集テキストが含まれています。ユーザーが[保存]ボタンをクリックすると、値が共有設定に配列として保存され、ユーザーが[読み取り]ボタンをクリックすると、共有で使用可能な配列から値が読み取られます。設定。

ステップ3 −次のコードを src / MainActivity.javaに追加します

package com.example.andy.myapplication;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      final ArrayList<String> arrPackage;
      setContentView(R.layout.activity_main);
      final SharedPreferences sharedPreferences = getSharedPreferences("USER",MODE_PRIVATE);
      final EditText name = findViewById(R.id.name);
      final EditText address = findViewById(R.id.address);
      final TextView result = findViewById(R.id.result);
      Button save = findViewById(R.id.button);
      Button read = findViewById(R.id.read);
      arrPackage = new ArrayList<>();
      read.setOnClickListener(new View.OnClickListener() {
         @SuppressLint("LongLogTag")
         @Override
         public void onClick(View v) {
            Gson gson = new Gson();
            String json = sharedPreferences.getString("Set", "");
            if (json.isEmpty()) {
               Toast.makeText(MainActivity.this,"There is something error",Toast.LENGTH_LONG).show();
            } else {
               Type type = new TypeToken<List<String>>() {
            }.getType();
            List<String> arrPackageData = gson.fromJson(json, type);
            for(String data:arrPackageData) {
               result.setText(data);
            }
         }
      }
   });
   save.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         if(name.getText().toString().isEmpty() && address.getText().toString().isEmpty()) {
            Toast.makeText(MainActivity.this,"Plz Enter all the data",Toast.LENGTH_LONG).show();
         }else{
            String nameData = name.getText().toString().trim();
            String addressData = address.getText().toString().trim();
            arrPackage.add(nameData);
            arrPackage.add(addressData);
            Gson gson = new Gson();
            String json = gson.toJson(arrPackage);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("Set",json );
            editor.commit();
         }
      }
   });
}

上記のコードでは、arraylistをGSONに変換し、GSONデータを文字列として取得しています。

ステップ4 − GSONにアクセスするには、以下に示すように、build.gradleにGSONライブラリを追加する必要があります-

apply plugin: 'com.android.application'
android {
   compileSdkVersion 28
   defaultConfig {
      applicationId "com.example.andy.myapplication"
      minSdkVersion 15
      targetSdkVersion 28
      versionCode 1
      versionName "1.0"
      testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
   }
   buildTypes {
      release {
         minifyEnabled false
         proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
      }
   }
}
dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.google.code.gson:gson:2.8.5'
   implementation 'com.android.support:appcompat-v7:28.0.0'
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.2'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

ステップ5 −manifest.xmlを変更する必要はありませんアプリケーションを実行してみましょう。

実際のAndroidモバイルデバイスをコンピューターに接続していると思います。 android studioからアプリを実行するには、プロジェクトのアクティビティファイルの1つを開き、ツールバーの[実行]アイコンをクリックします。オプションとしてモバイルデバイスを選択し、デフォルトの画面を表示するモバイルデバイスを確認します-

AndroidでArrayListをSharedPreferencesに保存する方法は?

上記の例では、名前と住所を追加し、保存ボタンをクリックしました。

AndroidでArrayListをSharedPreferencesに保存する方法は?

上記の例では、読み取りボタンをクリックしました。テキストをテキストビューに追加します


  1. AndroidでGmailの添付ファイルを保存する方法

    以前はAndroidでGmailの添付ファイルを携帯電話に保存するのは非常に複雑でしたが、昨年のAndroidアプリのメジャーアップデート以降、非常に簡単になりました。携帯電話にダウンロードするために、添付ファイルを含む実際の電子メールスレッドにいる必要はありません! ここでは、AndroidにGmailの添付ファイルを保存するためのいくつかの方法を紹介します。 最新バージョンのGmailアプリでは、メールの受信トレイからメールの添付ファイルに直接アクセスできます。 注:[会話リストの密度]をタップしてから、関連する設定に変更します。 これで、Gmailの受信トレイに戻り、メールプレ

  2. AndroidでTwitterからGIFを保存する方法

    Twitter はソーシャル メディアの単なる定義を超えて、世界の出来事を知らせる以上の目的で使用されています。組織、有名人、政治家、学生など、誰もがプラットフォームを使用して自分の意見を表明し、宣伝しています。このマイクロ ブログ サイトでは、Twitter ハンドルを使用してタグ付けするだけで、一般の人でも有名人と交流できます。 . Twitter のメディア流入には、ビデオから写真、そして現在非常に人気のある GIF やミームまで、あらゆる形式が見られます。単語の発音方法に関する論争はさておき、これらのビデオの短いクリップは一致した意見です。 感情や考えを伝えるための長い文章の必要性に取