-1

I managed to create an instance variable class in my android app in order to save the visibility state of a bunch of ImageView. Is there anyway to save this variable permanently using SharedPreferences or something? I need to load the states even if the user restarts the app.

ImageState.java

public class ImageState {
    //some variables here
    public ImageState(Context context, int[] imageId, int space){
        //blah blah...
    }
    public void saveState(){
        //saving visibility to shared preferences
    }
    public void loadState(){
        //loading state
    }
}

MainActivity.java

public void save(View view){
    //initializing variables here
    //creating ImageState
    ImageState imageState = new ImageState(this, ids, count);
    imageState.saveState();
}

public void load(View view){
   if(ImageState!=null) ImageState.loadState();
}

How can I save imageState?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

0

You can only save primitive data persistently. Integers, Strings can be stored but context cannot be stored in SharedPrefs. I would advise you to save all the primitives in SharedPreferences and then reinitialize ImageState with new context and data from SharedPreferences. Use this code to store data in sharedprefs

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, 
MODE_PRIVATE).edit();
editor.putInt("space", space);
editor.apply();

If you want to store integer array refer to this answer https://stackoverflow.com/a/47120128/4260786

Suhaib Roomy
  • 2,501
  • 1
  • 16
  • 22
  • Doesn't re-initializing ImageState reset all data? I have an array of SharedPreferences to store visibility for each ImageView, and it definitely needs the same ImageState to load it – Sepehr Mohammadi Jul 20 '18 at 15:01
  • yes it does. but you will have to put back the state of ImageState as it was using sharedpreferences after re-initializing it. You can also store the whole json of ImageState and then reinitialize using GSON but you will have to manage some variables like context regardless of what mechanism you use – Suhaib Roomy Jul 20 '18 at 15:04