【问题标题】:Android ArrayList of custom objects - Save to SharedPreferences - Serializable?自定义对象的 Android ArrayList - 保存到 SharedPreferences - 可序列化?
【发布时间】:2013-02-05 12:51:36
【问题描述】:

我有一个对象的 ArrayList。该对象包含“Bitmap”和“String”类型,然后是两者的getter 和setter。首先Bitmap是否可以序列化?

我将如何将其序列化以将其存储在 SharedPreferences 中?我看到很多人问过类似的问题,但似乎没有一个给出好的答案。如果可能的话,我更喜欢一些代码示例。

如果位图不可序列化,那么我该如何存储这个 ArrayList?

【问题讨论】:

  • SharedPreferences 的缺点是您不能在其中存储对象,因此无法存储对象:(
  • 序列化可以使用this answer。不过,我不知道这对SharedPreferences 有何帮助,因为您不能只在其中存储序列化对象。也许您正在考虑Bundle
  • 是的,您可以保存。检查我的答案。

标签: android arraylist sharedpreferences serializable


【解决方案1】:

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

 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);

更多信息,请点击here.

如果您想取回任何类型对象的 ArrayList,例如Student,然后使用:

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

【讨论】:

  • JSON数组名存入prefs时如何填写?
  • 你是什么意思?请详细说明您的问题。?
  • 如果您想保存 ARRAYLIST,此代码不起作用
  • @Bhavik Metha,上面写的代码不适用于 Arraylists,上面的代码只是示例。如果您想获取任何对象 e.d 学生类型的数组列表,那么我们: Type type = new TypeToken>(){}.getType(); List students= gson.fromJson(json, type);
  • 好主意。惊人的。谢谢。
【解决方案2】:

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

要保存对象列表,请这样做:

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);

【讨论】:

  • 这里Type的包是什么?
  • 导入 java.lang.reflect.Type;
  • 如果我使用通配符会怎样:Type type = new TypeToken&lt;List&lt;?&gt;&gt;(){}.getType(); 结果我得到一个 LinkedTreeMap,这是我的方法的定义:public static List&lt;?&gt; getList(String json) {
【解决方案3】:

对我来说它是这样工作的:

将值放入 SharedPreferences 中:

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();

从 SharedPreferences 中获取值:

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

【讨论】:

    【解决方案4】:

    保存:

    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 是我的自定义对象的名称。 (包含 String、long 和 boolean 值)

    【讨论】:

    • 我们不应该使用apply 而不是commit 吗?
    • 我们需要把这些方法调用放在哪里?
    【解决方案5】:

    上面的“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
    }
    

    【讨论】:

      【解决方案6】:

      Gson 的 kotlin 实现,扩展了@SpyZips 的答案,

      序列化为 JSON

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

      反序列化到 obj 列表

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

      【讨论】:

        【解决方案7】:

        解决方案

        别担心,您可以按照我的代码进行操作。我正在使用自己的 sharedPreference 自定义类来在 sharedPreference 中保存任何类型的 List。

        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_);
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2018-09-16
          • 2013-01-20
          • 1970-01-01
          • 2017-12-28
          • 2018-07-31
          • 1970-01-01
          • 2011-08-14
          • 1970-01-01
          • 2016-01-05
          相关资源
          最近更新 更多