androidinstancestate

Using onSaveInstanceState to prevent network call a second time


In my OnCreate method I am making a network call and populating a listview with the results. I am saving the result in an ArrayList and using the ArrayList to populate the listview. If the user presses the back button and reenters the activity I would like to store the ArrayLists in a SavedInstanceState Bundle and populate the ListView with the stored ArrayLists instead of making the network call a second time. The following is my OnCreate code:

      if (savedInstanceState != null) {

      largeImage = savedInstanceState.getParcelableArrayList("Image");
      flowercode = savedInstanceState.getStringArrayList("Code");
      flowerprice = savedInstanceState.getStringArrayList("Price");
      flowerdimensions = savedInstanceState.getStringArrayList("Dimension");
      largeImageText = savedInstanceState.getStringArrayList("Imagetext");

        ListView listView = (ListView) findViewById(R.id.LowRomance);
        FlowerShopAdapter listAdapter = new FlowerShopAdapter(this, flowercode, flowerName, flowerprice, largeImage, flowerdimensions);
        listView.setAdapter(listAdapter);

    } else if(savedInstanceState == null) {

            makesoapcall();

        }
    }

This is my OnSaveInstanceState code

   public void onSaveInstanceState(Bundle savedInstanceState) {
   savedInstanceState.putParcelableArrayList("Image", largeImage);
   savedInstanceState.putStringArrayList("Code", flowercode);
   savedInstanceState.putStringArrayList("Price", flowerprice);
   savedInstanceState.putStringArrayList("Dimension", flowerdimensions);

   super.onSaveInstanceState(savedInstanceState);

   }

Currently my App is making the network call every single time. Is their something else I need to implement in order to get this to work or is their an error in the current way I am trying to implement this? The ArrayList's are definitely not null when I put them into savedInstanceState.


Solution

  • onSaveInstanceState() is not supposed to be called when the back button is pressed on an Activity. It's called when Android decides to destroy the Activity.

    e.g. When orientation changes.

    What you need here is SharedPreferences. Store the ArrayLists using SharedPreferences in onStop(). And get it in onStart(). Here is how to store ArrayList in SharedPreferences.