[英]How to save Fragment recyclerview data on change fragment?
I have been trying to use onStateInstance but always return null and i dont know how to use ViewModel.我一直在尝试使用 onStateInstance 但总是返回 null 并且我不知道如何使用 ViewModel。
Im getting data from db to recyclerview and i dont want to download again data when navigate to another fragment.我从 db 获取数据到 recyclerview,我不想在导航到另一个片段时再次下载数据。 (I will update data with swipeRefreshLayout).
(我将使用 swipeRefreshLayout 更新数据)。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v =inflater.inflate(R.layout.fragment_search, container, false);
initComponents(v);
initRecyclerViewDB(v);
return v;
}
I need to save my list and dont call method initRecyclerView if my list is not null.如果我的列表不是 null,我需要保存我的列表并且不要调用方法 initRecyclerView。
public void initRecyclerViewDB(View v){
db.collection("post").orderBy("postBy", Query.Direction.ASCENDING).whereNotEqualTo("postBy",mAuth.getCurrentUser().getUid())
.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
postList.clear();
for (DocumentSnapshot ds:queryDocumentSnapshots.getDocuments()) {
postList.add(ds.toObject(Post.class));
}
postAdapter.notifyDataSetChanged();
}
});
In resume i want to save an arraylist to put in my recyclerview.在简历中,我想保存一个 arraylist 以放入我的 recyclerview。
The answer was using a view model:答案是使用视图 model:
public class YourViewModel extends ViewModel {
private final MutableLiveData<ArrayList<Post>> selectedItem = new MutableLiveData<>();
public void setData(ArrayList<YourList> item){
selectedItem.setValue(item);
}
public LiveData<ArrayList<YourList>> getSelectedItem(){
return selectedItem;
}
}
OnCreateView:在创建视图时:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v =inflater.inflate(R.layout.fragment_search, container, false);
viewModel = new ViewModelProvider(requireActivity()).get(PostViewModel.class);
viewModel.getSelectedItem().observe(getViewLifecycleOwner(), new Observer<ArrayList<Post>>() {
@Override
public void onChanged(ArrayList<Post> posts) {
postList.clear();
postList.addAll(posts);
postAdapter.notifyDataSetChanged();
}
});
if (postList.isEmpty()){
initRecyclerViewDB(v);
}else {
Toast.makeText(getContext(), "Save", Toast.LENGTH_SHORT).show();
}
initComponents(v);
return v;
}
If list is empty will import data from db, if not will use viewModel.如果列表为空将从数据库导入数据,否则将使用 viewModel。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.