如何在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