Android Studio: 使用SharedPreferences保存和加载ArrayList
创始人
2024-08-17 02:30:12
0

要使用SharedPreferences保存和加载ArrayList,可以按照以下步骤进行操作:

  1. 首先,在项目的build.gradle文件中添加依赖项,以确保可以使用SharedPreferences:
implementation 'androidx.preference:preference:1.1.1'
  1. 创建一个辅助类来处理SharedPreferences的保存和加载操作。在这个辅助类中,添加以下方法:
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;

public class SharedPreferencesHelper {

    private static final String KEY_ARRAYLIST = "arraylist_key";

    public static void saveArrayList(Context context, ArrayList arrayList) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(arrayList);
        editor.putString(KEY_ARRAYLIST, json);
        editor.apply();
    }

    public static ArrayList loadArrayList(Context context) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        Gson gson = new Gson();
        String json = sharedPreferences.getString(KEY_ARRAYLIST, null);
        Type type = new TypeToken>() {}.getType();
        return gson.fromJson(json, type);
    }
}
  1. 在需要保存ArrayList的地方调用saveArrayList方法,传入ArrayList参数:
ArrayList arrayList = new ArrayList<>();
arrayList.add("Item 1");
arrayList.add("Item 2");
SharedPreferencesHelper.saveArrayList(context, arrayList);
  1. 在需要加载ArrayList的地方调用loadArrayList方法:
ArrayList loadedArrayList = SharedPreferencesHelper.loadArrayList(context);

这样,你就可以使用SharedPreferences保存和加载ArrayList了。请注意,这里使用了Gson库来将ArrayList转换为JSON字符串进行保存,以及将JSON字符串转换回ArrayList进行加载。

相关内容

热门资讯

三分钟了解!微乐小程序自建房辅... 三分钟了解!微乐小程序自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)脚本1、每一步都需要思考...
玩家攻略!微信卡五星辅助器,微... 玩家攻略!微信卡五星辅助器,微乐自建房脚本免费入口(开挂自建房)攻略1、打开软件启动之后找到中间准星...
教程辅助!微乐微信自建房辅助工... 教程辅助!微乐微信自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)工具所有人都在同一条线上,像...
科技新动态!微信雀神麻将挂件开... 科技新动态!微信雀神麻将挂件开挂辅助,微乐小程序免费黑科技(开挂自建房)方法1、在微信雀神麻将挂件开...
教学盘点!微乐自建房辅助工具挂... 教学盘点!微乐自建房辅助工具挂,微乐家乡麻将自建房辅助app(开挂自建房)方法1、微乐家乡麻将自建房...
终于懂了!微乐小程序麻将自建房... 终于懂了!微乐小程序麻将自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)教程1、微乐小...
推荐攻略!微乐自建房辅助工具脚... 推荐攻略!微乐自建房辅助工具脚本,微乐自建房脚本免费入口(开挂自建房)教程推荐攻略!微乐自建房辅助工...
揭秘一下!微乐小程序自建房辅助... 揭秘一下!微乐小程序自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)攻略1、微乐小程序...
一分钟了解!微乐小程序麻将自建... 一分钟了解!微乐小程序麻将自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)攻略1)微乐小程序...
玩家必备科技!微乐自建房辅助工... 玩家必备科技!微乐自建房辅助工具挂,微乐小程序免费黑科技(开挂自建房)技巧1、打开软件启动之后找到中...