How correct is it to save objects in SP (I translate an object into gson and save it as a string)?
In the application, I turn from the fragment to the activit and I need to save 3 objects that were created in the fragment, and when I return back to the fragment from the activit, I get these objects.

Maybe there is an easier way to save objects?

  • one
    You can save objects in SP in theory, but I think in your case this is unnecessary. In theory, objects from a fragment into an activit can be done using the getter method. Show a piece of code, so it will be clearer - Werder

1 answer 1

If you need to keep the state of a fragment between its displays, you must override the onSaveInstanceState fragment onSaveInstanceState . In your case, it will look something like this:

 @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(FIRST_OBJECT_KEY, firstObject); outState.putSerializable(SECOND_OBJECT_KEY, secondObject); } 

The data saved in this way can then be obtained in the onCreate fragment onCreate from its savedInstanceState parameter, like this:

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null && savedInstanceState.containsKey(FIRST_OBJECT_KEY)){ firstObject = savedInstanceState.getSerializable(FIRST_OBJECT_KEY); } else { // значит ничего не было сохранено ранее, // то есть видимо фрагмент еще ни разу не создавался } }