Computer >> Máy Tính >  >> Lập trình >> Android

Làm cách nào để lưu ArrayList vào SharedPreferences trên Android?


Trước khi đi vào sở thích chia sẻ để lưu trữ ví dụ về danh sách mảng, chúng ta nên biết sở thích chia sẻ trong android là gì. Sử dụng sở thích chia sẻ, chúng tôi có thể lưu trữ hoặc truy xuất các giá trị dưới dạng cặp khóa và giá trị. Có năm phương pháp khác nhau có sẵn trong sở thích cổ phần như được hiển thị bên dưới -

  • Chỉnh sửa () - Nó sẽ chỉnh sửa các giá trị tùy chọn được chia sẻ

  • cam kết () - nó sẽ cam kết các giá trị ưu tiên được chia sẻ trong tệp xml

  • áp dụng () - Nó sẽ cam kết trở lại các thay đổi từ trình chỉnh sửa thành tùy chọn được chia sẻ.

  • xóa (Khóa chuỗi) - Nó sẽ xóa khóa và giá trị khỏi khóa sử dụng tùy chọn được chia sẻ.

  • Đặt () - Nó sẽ đặt khóa và giá trị cho xml tùy chọn chia sẻ.

Cú pháp mẫu ví dụ về sở thích được chia sẻ như được hiển thị bên dưới -

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

Trong cú pháp trên, chúng tôi đã tạo tệp tùy chọn chia sẻ dưới dạng USER.xml và nó ở chế độ riêng tư có nghĩa là không ứng dụng nào khác có thể truy cập tùy chọn được chia sẻ này.

Ví dụ dưới đây minh họa về cách sử dụng tùy chọn chia sẻ trong android.

Bước 1 - Tạo một dự án mới trong Android Studio, đi tới Tệp ⇒ Dự án Mới và điền tất cả các chi tiết cần thiết để tạo một dự án mới.

Bước 2 - Thêm mã sau vào 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>

Trong xml ở trên, nó chứa hai văn bản chỉnh sửa cho tên và địa chỉ, khi người dùng nhấp vào nút lưu, nó sẽ lưu trữ các giá trị dưới dạng một mảng trong tùy chọn được chia sẻ và khi người dùng nhấp vào nút đọc, nó sẽ đọc các giá trị từ mảng có sẵn trong chia sẻ sở thích.

Bước 3 - Thêm mã sau vào 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();
         }
      }
   });
}

Trong đoạn mã trên, chúng tôi đã chuyển đổi danh sách mảng thành GSON và lấy dữ liệu GSON dưới dạng chuỗi.

Bước 4 - Để truy cập GSON chúng ta cần thêm Thư viện GSON trong build.gradle như hình dưới đây -

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'

Bước 5 - Không cần thay đổi tệp kê khai.xml Hãy thử chạy ứng dụng của bạn.

Tôi cho rằng bạn đã kết nối thiết bị Di động Android thực với máy tính của mình. Để chạy ứng dụng từ android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Chạy từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn, sau đó kiểm tra thiết bị di động sẽ hiển thị màn hình mặc định của bạn -

Làm cách nào để lưu ArrayList vào SharedPreferences trên Android?

Trong ví dụ trên, chúng tôi đã thêm tên và địa chỉ và nhấp vào nút lưu.

Làm cách nào để lưu ArrayList vào SharedPreferences trên Android?

Trong ví dụ trên, chúng tôi đã nhấp vào nút đọc. nó sẽ nối văn bản vào chế độ xem văn bản