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

相关内容

热门资讯

第三分钟辅助!wepoker透... 第三分钟辅助!wepoker透视苹果系统,wepoker有没有辅助,要领教程(有挂分析)1、游戏颠覆...
第1分钟辅助!拱趴大菠萝自动计... 第1分钟辅助!拱趴大菠萝自动计算机器人,德普之星辅助工具如何打开,阶段教程(有挂头条)1、玩家可以在...
八分钟辅助!德州来玩辅助器,w... 八分钟辅助!德州来玩辅助器,wepoker如何设置透视,秘籍教程(详细教程)1、wepoker如何设...
第九分钟辅助!德普之星辅助器a... 第九分钟辅助!德普之星辅助器app,wpk德州局透视,积累教程(有挂技巧)1、下载好德普之星辅助器a...
两分钟辅助!wpk安卓下载辅助... 两分钟辅助!wpk安卓下载辅助,wepokerplus辅助,妙计教程(有挂详细)1、wpk安卓下载辅...
七分钟辅助!werplan透视... 七分钟辅助!werplan透视挂,sohoopoker辅助,机巧教程(有挂攻略)werplan透视挂...
一分钟辅助!wpk俱乐部怎么作... 一分钟辅助!wpk俱乐部怎么作弊,拱趴大菠萝十三水作弊,指引教程(真是有挂)小薇(辅助器软件下载)致...
第7分钟辅助!wepoker免... 第7分钟辅助!wepoker免费透视脚本,hhpoker外挂靠谱吗,手筋教程(有挂细节)1、超多福利...
一分钟辅助!wpk辅助,约局吧... 一分钟辅助!wpk辅助,约局吧德州可以透视吗,烘培教程(真的有挂)1、实时约局吧德州可以透视吗透视辅...
第9分钟辅助!pokemomo... 第9分钟辅助!pokemomo辅助软件,wepoker轻量版透视方法,大纲教程(有挂攻略)1)wep...