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、微乐自建房脚本免费入口有没...
3分钟辅助!决战卡五星辅助软件... 3分钟辅助!决战卡五星辅助软件哪个好用,竟然存在有辅助教程(揭秘有挂)1、在决战卡五星辅助软件哪个好...
五分钟辅助!微乐家乡游戏攻略,... 五分钟辅助!微乐家乡游戏攻略,好像是有辅助软件(有挂技巧)1、上手简单,内置详细流程视频教学,新手小...
1分钟辅助!一乐棋牌辅助器,其... 1分钟辅助!一乐棋牌辅助器,其实真的是有辅助工具(有挂详情)1、许多玩家不知道一乐棋牌辅助器辅助怎么...
第六分钟辅助!陕麻圈有挂吗,竟... 第六分钟辅助!陕麻圈有挂吗,竟然真的是有辅助工具(真的有挂)1、起透看视 陕麻圈有挂吗辅助软件价格2...
4分钟辅助!微乐麻辣自建房辅助... 4分钟辅助!微乐麻辣自建房辅助视频,一直存在有辅助教程(揭秘有挂)1、进入到微乐麻辣自建房辅助视频是...
第6分钟辅助!陕麻圈免费辅助工... 您好,陕麻圈免费辅助工具这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多...
3分钟辅助!白金岛手游放炮罚辅... 3分钟辅助!白金岛手游放炮罚辅助,原来真的是有辅助器(有挂教学)1、3分钟辅助!白金岛手游放炮罚辅助...
第二分钟辅助!台州夜猫十三道辅... 第二分钟辅助!台州夜猫十三道辅助器,一贯是真的有辅助工具(有挂方法)小薇(辅助器软件下载)致您一封信...
三分钟辅助!一乐浙江辅助软件,... 三分钟辅助!一乐浙江辅助软件,好像真的是有辅助脚本(有挂存在)1、下载好一乐浙江辅助软件透视辅助下载...