I have been trying to use onStateInstance but always return null and i dont know how to use ViewModel.
Im getting data from db to recyclerview and i dont want to download again data when navigate to another fragment. (I will update data with 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.
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.
The answer was using a view 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.