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

相关内容

热门资讯

我来教大家!菠萝德州透视脚本,... 我来教大家!菠萝德州透视脚本,cloudpoker作弊,好像是真的有挂(详细教程)1、上手简单,内置...
第三方技巧!哈糖大菠萝攻略,如... 第三方技巧!哈糖大菠萝攻略,如何下载德普之星辅助软件,好像确实有挂(发现有挂)1、超多福利:超高返利...
研究成果!wepoker怎么破... 研究成果!wepoker怎么破解游戏,拱趴大菠萝有挂吗,好像真的是有挂(有挂实锤)1、打开软件启动之...
长期以来!pokemmo修改器... 长期以来!pokemmo修改器手机版,德扑圈透视挂,真是是真的有挂(有挂详细)1、每一步都需要思考,...
如何分辨真伪!we-poker... 如何分辨真伪!we-poker有人玩吗,aapoker辅助工具安全吗,其实有挂(竟然有挂)1、公共底...
此事备受玩家关注!wepoke... 此事备受玩家关注!wepoker怎么设置盖牌,如何下载德普之星辅助软件,竟然真的是有挂(有挂详情)1...
推荐一款!aapoker透视怎... 推荐一款!aapoker透视怎么用,德州局透视脚本免费版下载手机版,一贯真的有挂(有挂规律)1、该软...
突发!智星德州有脚本吗,德普之... 突发!智星德州有脚本吗,德普之星透视,确实真的有挂(证实有挂)1、下载好智星德州有脚本吗透视辅助下载...
盘点十款!hhpoker有后台... 盘点十款!hhpoker有后台操作吗,wepoker私人局怎么玩,确实是有挂(有挂详细)1、让任何用...
无独有偶!hhpoker万能辅... 无独有偶!hhpoker万能辅助器,德普之星私人局辅助免费,原来存在有挂(存在有挂)1、这是跨平台的...