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

时间:2013-02-20 13:38:03

标签: android arraylist sharedpreferences serializable

我有一个对象的ArrayList。该对象包含类型'位图'和' String'然后只是两者的吸气剂和二传手。首先是Bitmap可序列化?

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

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

非常感谢。

10 个答案:

答案 0 :(得分:126)

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

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

答案 1 :(得分:110)

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

对于保存对象列表,请执行以下操作:

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

答案 2 :(得分:20)

对我而言,它的工作原理如下:

将值放在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());

答案 3 :(得分:12)

保存:

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

答案 4 :(得分:2)

解决方案

别担心,您可以按照我的代码进行操作。我正在使用自己的 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_);
    }
}

答案 5 :(得分:1)

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

序列化为JSON

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

反序列化回到objs列表

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

答案 6 :(得分:0)

在共享首选项中编写代码:

public class MySharedPrefernce {

        private Context context;
        private String PREF_NAME = "UserPreference";
        private int PRIVATE_MODE = 0;
        private SharedPreferences preferences;
        private SharedPreferences.Editor editor;
        private DataKey = "CART_RESTAURANTS";

        //constructor
        public MySharedPrefernce(Context context) {
            this.context = context;
            this.preferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
            editor = preferences.edit();
        }

        //add data
        public void saveRestaurantToSharedPrefs(List<CartRestaurantModel> cartRestaurantModel) {
            Gson gson = new Gson();
            String jsonCart = gson.toJson(cartRestaurantModel);
            editor.putString(DataKey, jsonCart);
            editor.commit();
        }

        //get data
        public ArrayList<CartRestaurantModel> getRestaurantToSharedPrefs() {
            List<CartRestaurantModel> cartData;
            if (preferences.contains(DataKey)) {
                String jsonCart = preferences.getString(DataKey, null);
                Gson gson = new Gson();
                CartRestaurantModel[] cartItems = gson.fromJson(jsonCart,
                        CartRestaurantModel[].class);

                cartData = Arrays.asList(cartItems);
                cartData = new ArrayList<CartRestaurantModel>(cartData);
            } else {
                try {
                    return new ArrayList<CartRestaurantModel>();
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
            return (ArrayList<CartRestaurantModel>) cartData;
        }

        //clear data
        public void clearRestaurantSharedPrefsData() {
            editor.clear();
            editor.commit();
        }
}

在您的活动/片段中编写代码以存储和检索:

public List<CartRestaurantModel> cartRestaurantModel = new ArrayList<CartRestaurantModel>();  // to maintain restaurant for cart menus

待店:

new MySharedPrefernce(this).saveRestaurantToSharedPrefs(cartRestaurantModel);

要检索:

cartRestaurantModel = new MySharedPrefernce(this).getRestaurantToSharedPrefs();

答案 7 :(得分:0)

##对于单次调用和检索列表,请使用##     `     列表模型=新的ArrayList <>();

Gson gson = new Gson();

String value= gson.toJson(models);

PreferenceManager.getDefaultSharedPreferences(context).edit().putString(value, "StringValueToRetrieve").apply();

要检索列表,请执行以下操作

 String value=PreferenceManager.getDefaultSharedPreferences(context).getString("StringValueToRetrieve", "noValue");

if(!value.contains("noValue")){

Gson gson = new Gson();

List<Model> models= gson.fromJson(value, 
    new TypeToken<List<Model>>(){}.getType());
}
`

答案 8 :(得分:0)

假设您有一个名为“药物治疗”的课程。您可以使用以下功能:

public static void saveMedicineToList(Medication medication){
            ArrayList<Medication> medicationArrayList = getListOfMedication();
            if(medicationArrayList == null) medicationArrayList = new ArrayList<>();
            medicationArrayList.add(medication);
            saveListOfMedicine(medicationArrayList);
        }

    public static void saveListOfMedicine(ArrayList<Medication> medicationArrayList){
        SharedPreferences shref;
        SharedPreferences.Editor editor;
        shref = PreferenceManager.getDefaultSharedPreferences(SakshamApp.getInstance());

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

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

    public static ArrayList<Medication> getListOfMedication(){
        SharedPreferences shref = PreferenceManager.getDefaultSharedPreferences(SakshamApp.getInstance());
        Gson gson = new Gson();
        String response=shref.getString(KEY_MIDICINES_LIST , "");
        ArrayList<Medication> medicationArrayList = gson.fromJson(response,
                new TypeToken<List<Medication>>(){}.getType());
        return medicationArrayList;
    }

答案 9 :(得分:0)

上面的“ Mete”示例就像一个魅力一样。
这是一个科特林示例

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
}