Saving state of custom object ArrayList

Viewed 49

I would like to restore the state of my array after a change of orientation. But I don't see an aproprieted function for this case. What shoul I do?

public class PuzzlePiece extends android.support.v7.widget.AppCompatImageView {
    public int xCoord;
    public int yCoord;
    public int pieceWidth;
    public int pieceHeight;
    public boolean canMove = true;

    public PuzzlePiece(Context context) {
        super(context);
    }

This is my onSave method

@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);    
        outState.putParcelableArray("image", pieces);
    }
}

And data initalization:

ArrayList<PuzzlePiece> pieces;
1 Answers

Basically speaking, you need to implement two methods: saveData() and loadData(). These will use GSON library in order to transform any object into a string and then re-create them back. Then you save and restore your objects where ever you need. You may do so when onPause() method is called, or anywhere else.

Here is the code:

Firstly, add the following dependency line in your build.gradle:

implementation 'com.google.code.gson:gson:2.8.6'

Then you write those two methods

 private void saveData(){
    SharedPreferences sharedPreferences = getSharedPreferences("shared preferences id", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(arraylistOfYourObjects);
    editor.putString("data_id", json);
    editor.apply();
}

private void loadData(){
    SharedPreferences sharedPreferences = getSharedPreferences("shared preferences id", MODE_PRIVATE);
    Gson gson = new Gson();
    String json = sharedPreferences.getString("data_id", null);
    Type type = new TypeToken<ArrayList<YourObjectClass>>() {}.getType();
    arraylistOfYourObjects = gson.fromJson(json, type);
    if(arraylistOfYourObjects == null){
        arraylistOfYourObjects = new ArrayList<>();
    }
}

Here is a link to a complete video on how to do the whole thing with allthe details: https://www.youtube.com/watch?v=jcliHGR3CHo

Related