Android中自定义对象的ArrayList - 保存到SharedPreferences - 序列化?

80
我有一个对象的ArrayList。该对象包含类型“Bitmap”和“String”,并且只包含获取器和设置器。首先,“Bitmap”是可序列化的吗?如果是,那么如何将其序列化以存储在SharedPreferences中?我看到很多人问类似的问题,但没有人给出很好的答案。如果可能的话,我更喜欢一些代码示例。如果位图不可序列化,那么我该如何存储这个ArrayList?

SharedPreferences 的缺点是无法在其中存储对象,因此无法存储对象 :( - Abhinav Singh Maurya
要将其序列化,您可以使用此答案。但是,我不知道这如何帮助SharedPreferences,因为您不能在那里存储序列化对象。也许您想到的是一个Bundle - Geobits
1
是的,你可以保存。请检查我的答案。 - Mohammad Imran
8个回答

150

是的,您可以将复合对象保存在共享首选项中。假设...

 Student mStudentObject = new Student();
 SharedPreferences appSharedPrefs = PreferenceManager
             .getDefaultSharedPreferences(this.getApplicationContext());
 Editor prefsEditor = appSharedPrefs.edit();
 Gson gson = new Gson();
 String json = gson.toJson(mStudentObject);
 prefsEditor.putString("MyObject", json);
 prefsEditor.commit(); 

现在,您可以按如下方式检索对象:

 SharedPreferences appSharedPrefs = PreferenceManager
             .getDefaultSharedPreferences(this.getApplicationContext());
 Gson gson = new Gson();
 String json = appSharedPrefs.getString("MyObject", "");
 Student mStudentObject = gson.fromJson(json, Student.class);

如需更多信息,请单击这里

如果您想要获取任何类型对象的ArrayList,例如Student,请使用以下代码:

Type type = new TypeToken<List<Student>>(){}.getType();
List<Student> students = gson.fromJson(json, type);

如何在将JSON数组存储到prefs中时设置其名称? - Noman
你的意思是什么?请详细说明你的问题。 - Mohammad Imran
如果你想保存一个ARRAYLIST,这段代码是无法工作的。 - Bhavik Mehta
12
@Bhavik Metha,上面的代码并不是针对ArrayList的,它只是一个例子。如果你想要获取任何对象类型的ArrayList,例如学生对象,可以使用以下代码: Type type = new TypeToken<List<Student>>(){}.getType(); List<Student> students= gson.fromJson(json, type); - Mohammad Imran
1
很棒的想法。太棒了。谢谢。 - jojemapa
我该如何更新这个列表?有没有什么方法可以更新这个列表? - aslamhossin

124

上面的答案是有效的,但不能用于列表:

如果要保存对象的列表,请按照以下方法进行:

List<Cars> cars= new ArrayList<Cars>();
    cars.add(a);
    cars.add(b);
    cars.add(c);
    cars.add(d);

    gson = new Gson();
    String jsonCars = gson.toJson(cars);
    Log.d("TAG","jsonCars = " + jsonCars);

读取JSON对象:

Type type = new TypeToken<List<Cars>>(){}.getType();
List<Cars> carsList = gson.fromJson(jsonCars, type);

3
这里的“Type”包指什么? - Shajeel Afzal
9
导入java.lang.reflect.Type; - SpyZip
如果我使用通配符,类似于: Type type = new TypeToken<List<?>>(){}.getType();结果我得到了一个LinkedTreeMap,这是我的方法定义: public static List<?> getList(String json) { - f.trajkovski

25

对我而言,它是这样工作的:

将值放入SharedPreferances中:

String key = "Key";
ArrayList<ModelClass> ModelArrayList=new ArrayList();

SharedPreferences shref;
SharedPreferences.Editor editor;
shref = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

Gson gson = new Gson();
String json = gson.toJson(ModelArrayList);

editor = shref.edit();
editor.remove(key).commit();
editor.putString(key, json);
editor.commit();

从 SharedPreferances 获取值:

Gson gson = new Gson();
String response=shref.getString(key , "");
ArrayList<ModelClass> lstArrayList = gson.fromJson(response, 
    new TypeToken<List<ModelClass>>(){}.getType());

16

保存:

public static void saveSharedPreferencesLogList(Context context, List<PhoneCallLog> callLog) {
    SharedPreferences mPrefs = context.getSharedPreferences(Constant.CALL_HISTORY_RC, context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = mPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(callLog);
    prefsEditor.putString("myJson", json);
    prefsEditor.commit();
}

负载:

public static List<PhoneCallLog> loadSharedPreferencesLogList(Context context) {
    List<PhoneCallLog> callLog = new ArrayList<PhoneCallLog>();
    SharedPreferences mPrefs = context.getSharedPreferences(Constant.CALL_HISTORY_RC, context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = mPrefs.getString("myJson", "");
    if (json.isEmpty()) {
        callLog = new ArrayList<PhoneCallLog>();
    } else {
        Type type = new TypeToken<List<PhoneCallLog>>() {
        }.getType();
        callLog = gson.fromJson(json, type);
    }
    return callLog;
}

PhoneCallLog是我的自定义对象名称。(包含字符串、长整型和布尔值)


1
我们不应该使用 commit 而是使用 apply 吗? - driftking9987
我们需要将这些方法调用放在哪里? - Lucas Sousa

3

上面的 Mete 的示例非常成功。
这是一个 Kotlin 示例

private var prefs: SharedPreferences = context?.getSharedPreferences("sharedPrefs", MODE_PRIVATE)
    ?: error("err")
private val gson = Gson()

保存

fun saveObjectToArrayList(yourObject: YourObject) {
    val bookmarks = fetchArrayList()
    bookmarks.add(0, yourObject)
    val prefsEditor = prefs.edit()

    val json = gson.toJson(bookmarks)
    prefsEditor.putString("your_key", json)
    prefsEditor.apply()
}

阅读

fun fetchArrayList(): ArrayList<YourObject> {
    val yourArrayList: ArrayList<YourObject>
    val json = prefs.getString("your_key", "")

    yourArrayList = when {
        json.isNullOrEmpty() -> ArrayList()
        else -> gson.fromJson(json, object : TypeToken<List<Feed>>() {}.type)
    }

    return yourArrayList
}

1

使用 Kotlin 实现,扩展 @SpyZips 的答案,同时使用 Gson 库。

将对象序列化为 JSON

val jsonCars: String = Gson().toJson(cars);

将反序列化的内容转换为对象列表

val type = object: TypeToken<List<Car>>(){}.type
val carsList: List<Car> = Gson().fromJson(jsonCars, type)

0

您可以使用以下内容

public static String MyClassListToJsonString(List<MyClassEntry> myMyClassList){
    Gson myGson = new Gson();
    return myGson.toJson(myMyClassList);
}

public static List<MyClass> JsonStringToDepositList(String jsonString){
    Gson myGson = new Gson();
    Type type = new TypeToken<List<MyClassEntry>>(){}.getType();
    return myGson.fromJson(jsonString, type);
}

0

解决方案

不用担心,您可以跟随我的代码。我正在使用自己定制的sharedPreference类来保存任何类型的列表。

public class AuthPreference {
    private static final String MY_PREFERENCES = "MY_PREFERENCES";
    private static final int MODE = Context.MODE_PRIVATE;
    private static AuthPreference pref;
    private final SharedPreferences sharedPreference;
    private final SharedPreferences.Editor editor;

    @SuppressLint("CommitPrefEdits")
    public AuthPreference(Context context) {
        sharedPreference = context.getSharedPreferences(MY_PREFERENCES, MODE);
        editor = sharedPreference.edit();
    }

    public void clear() {
        editor.clear().commit();

    }

    //Here  save your api responce like YourModel arraylist

    public void saveDataResponce(ArrayList<YourModel> model_, String key) {
        SharedPreferences.Editor editor = sharedPreference.edit();
        Gson gson = new Gson();
        String json = gson.toJson(model_);
        editor.putString(key, json);
        editor.apply();
    }

//Here we get our api responce like YourModel arraylist.Using key value when you want to define.

    public ArrayList<YourModel> getDataResponce(String key) {
        Gson gson = new Gson();
        String json = sharedPreference.getString(key, null);
        Type type_ = new TypeToken<ArrayList<YourModel>>() {
        }.getType();
        return gson.fromJson(json, type_);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接