'How to save an ArrayList of Buttons in SharedPreferences [closed]
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ryan M |
