SavedState ViewModel Using SavedStateViewModelFactory



我正在谷歌关注这个代码实验室,但它无法保存数据。这是链接

https://codelabs.developers.google.com/codelabs/android-lifecycles/#6

活动类

public class SavedStateActivity extends AppCompatActivity {
private SavedStateViewModel mSavedStateViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saved_state_activity);
// Obtain the ViewModel
// mSavedStateViewModel = new ViewModelProvider(this).get(SavedStateViewModel.class);
mSavedStateViewModel = new ViewModelProvider(this,new SavedStateViewModelFactory(getApplication(),this)).get(SavedStateViewModel.class);
// Show the ViewModel property's value in a TextView
mSavedStateViewModel.getName().observe(this, new Observer<String>() {
@Override
public void onChanged(String savedString) {
((TextView)findViewById(R.id.saved_vm_tv))
.setText(getString(R.string.saved_in_vm, savedString));
}
});
// Save button
findViewById(R.id.save_bt).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String newName = ((EditText)findViewById(R.id.name_et)).getText().toString();
mSavedStateViewModel.saveNewName(newName);
}
});
}
}

视图模型类

public class SavedStateViewModel extends ViewModel {
private static final String NAME_KEY = "name";
private SavedStateHandle mState;
public SavedStateViewModel(SavedStateHandle savedStateHandle) {
mState = savedStateHandle;
}
// Expose an immutable LiveData
LiveData<String> getName() {
// getLiveData obtains an object that is associated with the key wrapped in a LiveData
// so it can be observed for changes.
return mState.getLiveData(NAME_KEY);
}
void saveNewName(String newName) {
// Sets a new value for the object associated to the key. There's no need to set it
// as a LiveData.
mState.set(NAME_KEY, newName);
}
}

如您所见,我已经SavedStateViewModelFactorymSavedStateViewModel = new ViewModelProvider(this,new SavedStateViewModelFactory(getApplication(),this)).get(SavedStateViewModel.class);

但是当我销毁应用程序并将其打开时,没有任何效果,数据仍然没有保留。

谷歌所说的保存状态的解决方案仍处于测试阶段。目前,持久化数据的唯一解决方案是使用 Room。

相关内容

  • 没有找到相关文章

最新更新