自定义对象ArrayList的保存状态

时间:2019-06-09 15:54:42

标签: android

我想在改变方向后恢复阵列的状态。但是我看不到这种情况的专有功能。我该怎么办?

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);
    }

这是我的onSave方法

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

数据初始化:

ArrayList<PuzzlePiece> pieces;

1 个答案:

答案 0 :(得分:-1)

基本上来说,你需要实现两个方法:saveData() 和 loadData()。这些将使用 GSON 库将任何对象转换为字符串,然后重新创建它们。然后您可以在任何需要的地方保存和恢复您的对象。您可以在调用 onPause() 方法或其他任何地方时这样做。

代码如下:

首先,在 build.gradle 中添加以下依赖行:

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

那你写这两个方法

 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<>();
    }
}

这是一个完整视频的链接,该视频介绍了如何使用所有细节完成整个操作: https://www.youtube.com/watch?v=jcliHGR3CHo

相关问题