当我的应用从后台进程返回时,它会丢失上次设置



我尝试使用ViewModel,见下文:

public class ViewDispoViewModel extends ViewModel {
@Nullable
private boolean swDispo = true;
private String mDateSelVM;
public String getDateSel() {
return mDateSelVM;
}
public void setDateSel(String mDateSelVM) {
this.mDateSelVM = mDateSelVM;
}
}

在MainActicvity中,我读到了getDateSel:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewdispoactivity);
mDateSel = viewdispoViewModel.getDateSel();
if (mDateSel == null) {
dateda = new Date();
datea = new Date();
} else {
try {
dateda = dateFormat.parse(mDateSel);
Calendar cal = Calendar.getInstance();
cal.setTime ( dateda );
cal.add(Calendar.DATE, -1);
dateda = cal.getTime();
datea = dateda;
//datea = dateFormat.parse(mDateSel);
} catch (ParseException e) {
e.printStackTrace();
}
}
}

当我更改数据时,我在视图模型中设置新数据 但是当我最小化应用程序并再次打开它时,mDateSel 为空。

viewdispoViewModel.setDateSel(dateFormat.format(dateda));

您感兴趣的坦克

您可以使用"共享首选项"来实现此目的

设置值示例

SharedPreferences pref =   
PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = pref.edit();
edit.putBoolean("swDispo", true);
edit.putString("mDateSelVM", "your_string");
edit.commit(); 

获取值示例

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
String username = pref.getString("mDateSelVM", "default value"); 
Boolean yourLocked = prefs.getBoolean("swDispo", false);

如何准确活动工作可以在这里找到 https://developer.android.com/guide/components/activities/activity-lifecycle

onPause in Activity - 将您的值保存在 SharedPreferences 或 Application(不是 Activity(中。

在活动中恢复 - 从此值更新微调器的选定项。 阅读有关活动的各种状态的信息

活动的各种状态

最新更新