public class MainActivity extends AppCompatActivity { private Disposable disposable; private Observable<ModelSearchItems> observableCache; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState==null){ observableCache=RequestApi.getSearchItems() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).cache(); } disposable=observableCache.subscribe(modelSearchItems -> { Log.e("MainActivity=onCreate", modelSearchItems.message.size() + ""); }); } @Override protected void onDestroy() { super.onDestroy(); disposable.dispose(); } } 

What am I doing wrong? On the Internet, I read an article about such an approach that the dude praised himself and everything worked for him ...

I get an error

  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'io.reactivex.disposables.Disposable io.reactivex.Observable.subscribe(io.reactivex.functions.Consumer)' on a null object reference MainActivity.onCreate(MainActivity.java:31) 
  • one
    I can assume that here if (savedInstanceState == null) something is not working and observableCache is still null . And why don't you just save it to savedInstanceState ? - kulikovman
  • @kulikovman, can you please sample code? - user239760

1 answer 1

To save and restore data while rotating the screen, use the onSaveInstanceState and onRestoreInstanceState . To keep your list of objects inside onSaveInstanceState you need to use Serializable (easier) or Parcelable (more productive).

In the end, it will look something like this:

 @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("key", (Serializable) mObservableCache); } @Override public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) { super.onRestoreInstanceState(savedInstanceState, persistentState); mObservableCache = (Observable<ModelSearchItems>) savedInstanceState.get("key"); } 

Also, perhaps reading this article will help.

  • the error is FATAL EXCEPTION: main Process: com.eranewgames.jeenchtest, PID: 31878 java.lang.ClassCastException: io.reactivex.internal.operators.observable.ObservableObserveOn cannot be cast to java.io.Serializable at MainActivity.onSaveInstanceState(MainActivity.java:40) - user239760