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进行加载。

相关内容

热门资讯

透视美元局!中至江西源代码,w... 透视美元局!中至江西源代码,wepoker游戏的安装教程(辅助挂)详细开挂辅助器1、下载安装好wep...
今日焦点!奇迹手游辅助,阿拉游... >>您好:阿拉游戏中心辅助工具确实是有挂的,很多玩家在这款阿拉游戏中心辅助工具游戏中打牌都会发现很多...
透视线上!浙江宝宝游戏辅助器,... 透视线上!浙江宝宝游戏辅助器,hhpoker作弊码怎么用(辅助挂)详细开挂辅助下载 了解更多开挂安装...
攻略讲解!极速官方暗堡透视,对... 您好:这款极速官方暗堡透视游戏是可以开挂的,确实是有挂的,很多玩家在这款极速官方暗堡透视游戏中打牌都...
透视好友!pokermaste... 透视好友!pokermaster破解版,wepoker辅助真的假的(辅助挂)详细开挂辅助神器;无需打...
信息共享!传送屋app辅助脚本... 大家好,今天小编来为大家解答传送屋app辅助脚本下载这个问题咨询软件客服可以免费测试直接加微信(13...
透视玄学!wepoker手机助... 您好:这款红龙poker辅助平台游戏是可以开挂的,确实是有挂的,很多玩家在这款红龙poker辅助平台...
新手必备!四川家园辅助器,陕麻... 新手必备!四川家园辅助器,陕麻圈有辅助吗(有挂方法辅助插件);无需打开直接搜索打开薇:1367043...
必知教程!潮汕娱手机暗宝透视,... 必知教程!潮汕娱手机暗宝透视,反杀大厅辅助(证实有挂开挂辅助下载);无需打开直接搜索薇:136704...
透视苹果版!德普之星透视辅助软... 透视苹果版!德普之星透视辅助软件激活码,wepoker到底有没有透视(辅助挂)详细开挂辅助器 了解更...