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

相关内容

热门资讯

德州免费辅助神器app!德扑a... 德州免费辅助神器app!德扑ai智能机器人线上代打,德扑其实有挂(详细插件教程)1、许多玩家不知道德...
we辅助poker德之星!we... 1、we辅助poker德之星!wepoke辅助软件下载链接,wopoker用ai有用,教你攻略(有挂...
wpk外 挂!WpK总是真的有... wpk外 挂!WpK总是真的有挂,wPK原来真的有挂,第三方教程(有挂技巧)进入游戏-大厅左侧-新手...
德州微扑克辅助!德扑ai助手软... 德州微扑克辅助!德扑ai助手软件,线上德州原来是有挂(详细智能教程)(1)德州微扑克辅助!德扑ai助...
wepower有外 挂!wep... wepower有外 挂!wepoke辅助软件下载,wepoKE都是真的有挂,必赢教程(有挂规律);科...
wpk透视辅助(WpK)wpk... wpk透视辅助(WpK)wpk数据清零(透视)好像真的有挂(系统教程)1、超多福利:超高返利,海量正...
德州AI智能辅助机器人!wep... 1、德州AI智能辅助机器人!wepower德州可以设置,德扑线上总是真的有挂(详细有作弊教程);代表...
WePoKe外 挂!wepow... WePoKe外 挂!wepower有辅助器(透明挂)WePoke(其实真的有挂)相信很多朋友都在电脑...
WPK透视辅助(Wpk)wpk... WPK透视辅助(Wpk)wpk微扑克辅助是真的(辅助挂)好像真的有挂(高科技教程)1、微扑克ai辅助...
德扑ai助手!德州软件辅助计算... 德扑ai助手!德州软件辅助计算,德州之星一贯真的是有挂(详细数据软件教程)1、不需要AI权限,帮助你...