我已声明我的ViewModel如下,其中我使用set方法存储数据并获取数据:
public class DataListViewModel extends ViewModel
{
private List<Object> dataList;
public DataListViewModel(){
dataList = new ArrayList<>();
}
void setDataList(List<Object> dataList) {
this.dataList = dataList;
}
List<Object> getDataList() {
return dataList;
}
}
我已经声明了如下视图模型:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_recipes);
// Defining view model to store saved recipes data
viewModel = ViewModelProviders.of(this).get(DataListViewModel.class);
if (savedInstanceState != null)
{
dataList = viewModel.getDataList();
if (dataList == null)
{
Log.i("SavedRecipes", "View Model not working");
}
else
{
Log.i("SavedRecipes", "ViewModel" + (viewModel.getDataList()));
}
}
}
在我的Activity的onSavedInstanceState中,我正在调用set方法来保存数据:
viewModel.setDataList(dataList);
如onCreate所示,当我调用viewmodel的get方法时,尽管设置dataList不为空,但我得到的是空白对象
答案 0 :(得分:0)
onSavedInstanceState()中出现错误,我使用的是onSavedInstanceState(Bundle,PersistableBundle)而不是onSavedInstanceState(Bundle)
答案 1 :(得分:-1)
尝试此代码,我得到了数据。
viewModel = ViewModelProviders.of(this).get(DataListViewModel.class);
String str = "xyz";
List<Object> obj = new ArrayList<>();
obj.add(str);
viewModel.setDataList(obj);
List<Object> getDataList = viewModel.getDataList();
if (getDataList != null && !getDataList.isEmpty()) {
for (Object data : getDataList) {
if (data instanceof String) {
Log.d("Data to show::", (String) data);
}
}
}