-1

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?

Ryan M
  • 18,333
  • 31
  • 67
  • 74
Simba
  • 51
  • 7
  • 1
    Close voters: How exactly does this need more focus? It is asking how to do a single thing. The fact that that thing is impossible does not make it lack focus. "You can't" is an answer. – Ryan M Feb 10 '22 at 05:23

1 Answers1

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.

Ryan M
  • 18,333
  • 31
  • 67
  • 74