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

前端 未结 11 1610
别跟我提以往
别跟我提以往 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 12:08

    Easy mode for complex object storage with using Gson google library [1]

    public static void setComplexObject(Context ctx, ComplexObject obj){
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("COMPLEX_OBJECT",new Gson().toJson(obj)); 
        editor.commit();
    }
    
    public static ComplexObject getComplexObject (Context ctx){
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
        String sobj = preferences.getString("COMPLEX_OBJECT", "");
        if(sobj.equals(""))return null;
        else return new Gson().fromJson(sobj, ComplexObject.class);
    }
    

    [1] http://code.google.com/p/google-gson/

提交回复
热议问题