Android 保存自定义对象ArrayList的状态
我想在方向改变后恢复阵列的状态。但我看不到一个合适的函数。我该怎么办Android 保存自定义对象ArrayList的状态,android,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 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;
ArrayList片段;
基本上,您需要实现两种方法: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<>();
}
}
private void saveData(){
SharedPreferences SharedPreferences=getSharedPreferences(“共享首选项id”,模式\私有);
SharedReferences.Editor=SharedReferences.edit();
Gson Gson=新的Gson();
字符串json=gson.toJson(arraylistOfYourObjects);
putString(“data_id”,json);
editor.apply();
}
私有void loadData(){
SharedPreferences SharedPreferences=getSharedPreferences(“共享首选项id”,模式\私有);
Gson Gson=新的Gson();
String json=SharedReferences.getString(“数据id”,null);
Type Type=new TypeTokenArrayList中的ImageView是否始终是活动布局的一部分?或者您是否保留它们以在必要时添加和删除它们?@0X0nosugar老实说,我不确定,我遵循的是这里提供的教程。我会说这种方法已经过时。使用视图模型
可以实现same结果几乎没有样板。你能分享一个链接吗?你可以只搜索大多数Android文档,但这里有一个链接:据我所知,ViewModel不让数据在你退出应用后继续存在。而保存在SharedReferences中则可以继续存在,包括退出应用,这是我的一个错误在很多情况下都可能需要。是的,你是对的,但问题是要坚持方向,所以这样做太过分了。