0

For a college project I need to develop an Android app that retrieves JSON data from an API and displays it in a RecyclerView. One of the app requirements is that the Asynctask shouldn't be re-executed after changing screen orientation. In other words, once the Asynctask is executed and the RecyclerView is displayed with the retrieved data, it shouldn't have to retrieve the data again after rotating the screen.

For demonstration purposes I've added a toast in the onPostExecute method that shows the amount of items that have been displayed:

enter image description here

enter image description here

As you can see, the toast reappears after rotating the screen, meaning the Asynctask was re-executed. I want to prevent this from happening, but I can't figure out how.

Stefan Jaspers
  • 461
  • 5
  • 16
  • Duplicate: https://stackoverflow.com/a/456918/2711811 - in particular see the "recommended alternative" reference for solution with fragments. –  Mar 07 '20 at 19:32

1 Answers1

1

Try to add this line to your activity tag of the Manifest file.

<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>

When you write this parameter you don't want to handle anything in activity but Android will take care of this. It will remain the existing state of the activity.

If you are using different layout files for landscape orientation this method will break your layouts, so you can follow some alternative methods to keep the state.

Override onSaveInstanceState method in your activity and add some param in the Bundle

protected void onSaveInstanceState(Bundle bundle) {
  super.onSaveInstanceState(bundle);
  bundle.putLong("param", value);
}

And restore the value in onCreate to make sure the state was already created.

public void onCreate(Bundle bundle) {
  if (bundle != null){
    value = bundle.getLong("param");
  }
}
Googlian
  • 6,077
  • 3
  • 38
  • 44