1

I'm trying the new Saved State module but without result, at the moment. This is the OnCreate of my Fragment:

@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppCompatActivity activity = (AppCompatActivity) requireActivity();
        viewModel = new SavedStateViewModelFactory(requireActivity().getApplication(), requireActivity()).create(QueryViewModel.class);
        //The following is code for debugging purposes
        List<SingleNote> list = viewModel.getState().get(KEY);
        Log.i("ONCREATE", "ONCREATE");
        if (list != null) {
            Log.i("NUMBER OF ELEMENTS", String.valueOf(list.size()));
        }
    }

and this is my ViewModel class:

public class QueryViewModel extends ViewModel {

    private SavedStateHandle state = new SavedStateHandle();

    public QueryViewModel(SavedStateHandle savedStateHandle) {
        state = savedStateHandle;
    }

    public SavedStateHandle getState() {
        return state;
    }

I save a List<> of Serializable object inside the SavedStatehandle and it works. The problem came when I start a new activity with StartActivity (it is an Activity of my app, not an external one) because when I return back the SavedStateHandle is empty.

Any suggest? I have added the correct dependencies and I've already tried the ViewModelProvider constructor.

Bender
  • 129
  • 3
  • Solved. The solution is explained here: https://stackoverflow.com/questions/12276027/how-can-i-return-to-a-parent-activity-correctly/15933890#15933890 – Bender Dec 08 '22 at 20:52

0 Answers0