I'd like to save a list of buttons in SharedPreferences but it doesn't work. The error message that occurs is "java.lang.IllegalArgumentException: class android.graphics.drawable.InsetDrawable declares multiple JSON fields named mState"
public boolean writeToSharedPreferences(Context context, ArrayList<Button> arrayList) {
String file = "list";
SharedPreferences mPrefs = context.getSharedPreferences(file, Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
prefsEditor.putString("list", json);
prefsEditor.commit();
return true;
}
public ArrayList<Button> readFromSharedPreferences(Context context) {
String file = "list";
SharedPreferences mPrefs = context.getSharedPreferences(file, Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = mPrefs.getString("list", "");
Type type = new TypeToken<List<Button>>(){}.getType();
ArrayList<Button> arrayList= gson.fromJson(json, type);
return arrayList;
}
Can someone help me pls?
CodePudding user response:
You can't.
Buttons are an interactive UI element. They have behaviors and code (what happens on click) associated with them. You can't save a Button to shared preferences any more than you can print one out on your printer: what you get would not be a Button, just an image of one that couldn't be pressed.
Consider what you're actually trying to save: is it some information about the state of the system? Some text? Save that to shared preferences, then rebuild your UI from that data when you read it back out.
CodePudding user response:
Your error points more about JSON conversion problem with the ArrayList of Buttons.
Could be similar problem to this. class A declares multiple JSON fields
Try new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(YOUR_OBJECT)
