android - 永久存储实例变量
问题描述
我设法在我的 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
?
解决方案
您只能永久保存原始数据。可以存储整数、字符串,但不能将上下文存储在 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
推荐阅读
- javascript - 读取在 JS 中创建的 Laravel Blade 中的 cookie
- java - 错误 405 - 在 Java HTTP 函数调用中找不到方法
- java - 无法找到或加载主类 com.simplilearn.testing.oops.LunchNewBrowser 原因:使用 Selenium Java 的 java.lang.ClassNotFoundException 错误
- reactjs - 在 ScrollView 中放置一个包含 FlatList 的组件以进行下拉刷新?
- powerbi - 如何将 YYYYMM 转换为日期时间或数字?
- matlab - 从 ployshape 类中提取值
- javascript - 嵌入被多次发送。如何让它只发送一次?
- c# - 在 Azure 函数中处理 NLog
- prolog - 显示所有大于 N 的列表元素 - Prolog
- apache-spark - Hive TRANSFORM 接收连接数组值的 NULL