如何在Android中將ArrayList儲存到SharedPreferences?
在學習如何使用Shared Preferences儲存ArrayList之前,我們應該瞭解Android中的Shared Preferences是什麼。使用Shared Preferences,我們可以以鍵值對的形式儲存或檢索值。Shared Preferences中有五種不同的方法,如下所示:
Edit() − 用於編輯Shared Preferences的值。
commit() − 將Shared Preferences的值提交到xml檔案。
apply() − 將編輯器中的更改提交回Shared Preferences。
remove(String key) − 使用鍵從Shared Preferences中刪除鍵值對。
Put() − 將鍵值對新增到Shared Preferences xml。
Shared Preferences的示例語法如下所示:
final SharedPreferences sharedPreferences = getSharedPreferences("USER",MODE_PRIVATE);在上面的語法中,我們建立了一個名為USER.xml的Shared Preferences檔案,它是私有模式,這意味著其他應用程式無法訪問此Shared Preferences。
以下示例演示如何在Android中使用Shared Preferences。
步驟1 − 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。
步驟2 − 將以下程式碼新增到res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://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中,它包含兩個用於姓名和地址的EditText,當用戶點選儲存按鈕時,它將值作為陣列儲存在Shared Preferences中,當用戶點選讀取按鈕時,它將讀取Shared Preferences中陣列中的值。
步驟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中執行應用程式,請開啟您的專案中的一個activity檔案,然後點選執行
工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕:

在上面的示例中,我們添加了姓名和地址,然後點選了儲存按鈕。

在上面的示例中,我們點選了讀取按鈕。它會將文字新增到TextView中。
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP