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

相关内容

热门资讯

2分钟辅助!创思维激k有挂吗,... 【亲,创思维激k有挂吗 这款游戏可以开挂的,确实是有挂的,很多玩家在这款创思维激k有挂吗中打牌都会发...
第十分钟辅助!wepoker亲... 第十分钟辅助!wepoker亲友圈有用吗,丹东约战麻将辅助器(一分钟了解开挂辅助脚本);亲真的是有正...
6分钟开挂!wepoker透视... 6分钟开挂!wepoker透视脚本下载,闲逸辅助脚本(透视透视开挂辅助神器);无需打开直接搜索微信(...
5分钟辅助!皮皮胡子辅助,潮友... 5分钟辅助!皮皮胡子辅助,潮友会虾蟹骰子概率计算方式(玩家必看开挂辅助安装);潮友会虾蟹骰子概率计算...
1分钟辅助!微信微乐有挂没有,... 1分钟辅助!微信微乐有挂没有,微信中至有辅助吗(透视有挂开挂辅助平台);相信小伙伴都知道这个微信中至...
第1分钟辅助!禅游游戏辅助,乐... 第1分钟辅助!禅游游戏辅助,乐平包王攻略(科普常识开挂辅助平台);大家肯定在之前乐平包王攻略或者乐平...
第9分钟开挂!广西微乐小程序脚... 第9分钟开挂!广西微乐小程序脚本,河洛杠次插件(最新技巧开挂辅助下载)【无需打开直接搜索加薇1367...
第4分钟辅助!贪玩互娱辅助,微... 第4分钟辅助!贪玩互娱辅助,微乐小程序挂哪里有(今日重大通报开挂辅助工具);相信小伙伴都知道这个微乐...
第七分钟开挂!欢聚水鱼天下辅助... 您好:这款欢聚水鱼天下辅助游戏是可以开挂的,确实是有挂的,很多玩家在这款欢聚水鱼天下辅助游戏中打牌都...
第四分钟辅助!xpoker透视... 第四分钟辅助!xpoker透视辅助,小闲川南手游辅助器(技巧知识分享开挂辅助安装);小薇(透视辅助)...