Is it possible to add an array or object to SharedPreferences on Android

前端 未结 11 1807
别跟我提以往
别跟我提以往 2020-11-22 11:27

I have an ArrayList of objects that have a name and an icon pointer and I want to save it in SharedPreferences. How can I do?

NOTE:

11条回答
  •  时光说笑
    2020-11-22 11:50

    To write,

    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    JSONArray jsonArray = new JSONArray();
    jsonArray.put(1);
    jsonArray.put(2);
    Editor editor = prefs.edit();
    editor.putString("key", jsonArray.toString());
    System.out.println(jsonArray.toString());
    editor.commit();
    

    To Read,

    try {
        JSONArray jsonArray2 = new JSONArray(prefs.getString("key", "[]"));
        for (int i = 0; i < jsonArray2.length(); i++) {
             Log.d("your JSON Array", jsonArray2.getInt(i)+"");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    

提交回复
热议问题