I have tablayout and 2 fragments in separate tabs.
Fragment A have an overridden method that returns data when Activity (started from Fragment A) return data on it's destroy:
public class Fragment A extends Fragment {
...
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(resultCode != RESULT_CANCELED) {
assert data != null;
String accountTransaction = data.getStringExtra("Account");
String categoryTransaction = data.getStringExtra("Category");
Double getDouble = data.getDoubleExtra("Value", 0);
TransactionNewItem item = new TransactionNewItem(String.valueOf(getDouble),accountTransaction,categoryTransaction);
model.setSelected(item);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
In this same method I use a call to ViewModel that should observe TransactionNewItem object :
public class TransactionViewModel extends ViewModel {
private final MutableLiveData<TransactionNewItem> selected = new MutableLiveData<>();
public void setSelected (TransactionNewItem item){
selected.setValue(item);
}
public LiveData<TransactionNewItem> getSelected() {
return selected;
}
}
After data that returns from Activity, with new values it creates a new POJO and sends data stored in this POJO to Fragment B, where based on data from Fragment A new item for RecyclerView will be created
public class Fragment B extends Fragment {
...
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
initObserve();
initRecView();
super.onViewCreated(view, savedInstanceState);
}
//init RecyclerView
private void initRecView(){
binding.transactionView.setLayoutManager(new LinearLayoutManager(requireContext()));
adapter = new TransactionRecViewAdapter(listContentArr);
adapter.setListContent(listContentArr);
binding.transactionView.setAdapter(adapter);
}
//observe data from Fragment A and create object based on it
private void initObserve(){
model = new ViewModelProvider(requireActivity()).get(TransactionViewModel.class);
model.getSelected().observe(getViewLifecycleOwner(), item -> {
TransactionItem newAccountItem = new TransactionItem() ;
newAccountItem.setTransactionValue(item.getTransactionValue());
newAccountItem.setTransactionCategory(item.getTransactionCategory());
newAccountItem.setTransactionAccount(item.getTransactionAccount());
listContentArr.add(0,newAccountItem);
adapter.notifyDataSetChanged();
});
}
}
However, it will add only 1 item into RecyclerView and will replace it with when Activity returns new data. This happens if the user didn’t switch to Fragment B at least one time, because onViewCreated isn't called till the user switches to Fragment B.
How to make ViewModel observe data from Fragment A, and create new TransActionItem in Fragment B Recyclerview every time the Activity returns new data if the user never switched to Fragment B before?
Thanks in advance