首页 > 解决方案 > 永久存储实例变量

问题描述

我设法在我的 android 应用程序中创建了一个实例变量类,以保存一堆ImageView. 有没有办法永久保存这个变量SharedPreferences?即使用户重新启动应用程序,我也需要加载状态。

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

我怎样才能保存imageState

标签: android

解决方案


您只能永久保存原始数据。可以存储整数、字符串,但不能将上下文存储在 SharedPrefs 中。我建议您将所有原语保存在 SharedPreferences 中,然后使用 SharedPreferences 中的新上下文和数据重新初始化 ImageState。使用此代码将数据存储在 sharedprefs 中

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

如果要存储整数数组,请参阅此答案https://stackoverflow.com/a/47120128/4260786


推荐阅读