Android 永久存储实例变量
我设法在我的android应用程序中创建了一个实例变量类,以保存一堆Android 永久存储实例变量,android,Android,我设法在我的android应用程序中创建了一个实例变量类,以保存一堆ImageView的可见性状态。是否仍然可以使用SharedReferences或其他方法永久保存此变量?我需要加载状态,即使用户重新启动应用程序 ImageState.java public class ImageState { //some variables here public ImageState(Context context, int[] imageId, int space){
ImageView
的可见性状态。是否仍然可以使用SharedReferences
或其他方法永久保存此变量?我需要加载状态,即使用户重新启动应用程序
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
}
}
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();
}
MainActivity.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
}
}
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();
}
如何保存
imageState
?您只能持久保存原始数据。整数,字符串可以存储,但上下文不能存储在SharedPref中。我建议您保存SharedReferences中的所有原语,然后使用SharedReferences中的新上下文和数据重新初始化ImageState。使用此代码在SharedPref中存储数据
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,
MODE_PRIVATE).edit();
editor.putInt("space", space);
editor.apply();
如果要存储整数数组,请参考此答案是否重新初始化ImageState重置所有数据?我有一个SharedReference数组来存储每个ImageView的可见性,它肯定需要相同的ImageState来加载它是的。但在重新初始化ImageState之后,您必须将其状态恢复为使用SharedReferences时的状态。您还可以存储ImageState的整个json,然后使用GSON重新初始化,但无论使用何种机制,都必须管理一些变量,如上下文