android onSaveInstanceState usage

Please guide in the following class what I should save in.

Please remember I am using only one string which is I am retriving from getextra method and there is nothing which I think I should store in the following overridden method.

protected void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub

Can you guide me what to store in onsave instance method and what not to?

package com.wozzon.activity;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.wozzon.json.JSONService;
import com.wozzon.model.SearchCriteria;
import com.wozzon.util.Util;
import com.wozzon.util.WLConstants;

public class HomeBrowse extends Activity implements OnItemClickListener{
    private final static String TAG = HomeBrowse.class.getSimpleName();
    private ArrayList<BrowseRow> model=new ArrayList<BrowseRow>();
    private BrowseAdapter adapter;
    private ListView list;
    private TextView browseTitle;
    private TextView changeLink;
    private SearchCriteria sc =SearchCriteria.getInstance();

    private JSONArray jsonArray;
    private ProgressDialog m_ProgressDialog = null; 
    private Runnable progressRunnable;

    public void onCreate(Bundle savedInstanceState) {
        try {
            String errorMsg =Util.getExtraValue(getIntent().getExtras(), WLConstants.ERROR_MSG); 
            list =(ListView)findViewById(;
            if(errorMsg!= null){
                UIFactory.displayAlert(new AlertDialog.Builder(HomeBrowse.this), "Status", errorMsg);
            progressRunnable = new Runnable(){
                public void run() {
                 try {

                    } catch (Throwable e) {
                        Log.e(TAG, e.getMessage());
            m_ProgressDialog =,    
                      "Please wait...", "Loading ...", true);
            Thread thread = new Thread(progressRunnable);
        } catch (Throwable e) {
            Log.e(TAG, e.getMessage());
            Util.handleError(HomeBrowse.this, HomeBrowse.class, e.getMessage());
            //UIFactory.displayAlert(new AlertDialog.Builder(HomeBrowse.this), "Error Loading categories", e.getMessage());

    private void loadData()throws Throwable{//loading object

        jsonArray = JSONService.getJsonArray(getResources().getString(R.string.catJson));

    private void fillResultRows(JSONArray jsonArray, BrowseAdapter adapter)throws Throwable{
        BrowseRow br = null;
        try {
            for(int a=0; a<jsonArray.length(); a++){
                JSONObject jsonObj = jsonArray.getJSONObject(a);
                br = new BrowseRow();
                br.searchType = jsonObj.getInt("searchType");

                    br.categoryIds = jsonObj.getString("categoryIds").replaceAll("-", ",");
                    br.subCategoryIds = jsonObj.getString("subCategoryIds").replaceAll("-", ",");
        } catch (Throwable e) {
            throw e;


    class BrowseAdapter extends ArrayAdapter<BrowseRow> {
        BrowseAdapter() {
            super(HomeBrowse.this, android.R.layout.simple_list_item_1, model);

        public View getView(int position, View convertView,
                                                ViewGroup parent) {
            View row=convertView;
            ResultWrapper wrapper=null;

            if (row==null) {                                                    
                LayoutInflater inflater=getLayoutInflater();

                row=inflater.inflate(R.layout.browse_row, null);
                wrapper=new ResultWrapper(row);
            else {

    class ResultWrapper {
        private TextView name;
        private String catIds="0";
        private String subCatIds="0";
        private ImageView image;
        private int searchType;

        private View row=null;

        ResultWrapper(View row) {

        void populateFrom(BrowseRow r) {
            catIds =r.categoryIds;
            subCatIds = r.subCategoryIds;
            searchType =r.searchType;
        TextView getName() {
            if (name==null) {
            return name;
        ImageView getIcon() {
            if (image==null) {
            return image;


    private int getImageIcon(int catId){

        int imageSource=R.drawable.all_cats;

        case WLConstants.CATEGORY_FILM: imageSource; break;  
        case WLConstants.CATEGORY_MUSIC: imageSource; break;
        case WLConstants.CATEGORY_ARTS: imageSource; break;
        case WLConstants.CATEGORY_KIDS: imageSource; break;
        case WLConstants.CATEGORY_GALLERY_MUSEUM: imageSource; break;
        case WLConstants.CATEGORY_COMEDY: imageSource =R.drawable.comedy; break;
        case WLConstants.CATEGORY_NIGHT_CLUBS: imageSource =R.drawable.clubs; break;
        case WLConstants.CATEGORY_ATTRACTION: imageSource =R.drawable.touristattractions; break;
        case WLConstants.CATEGORY_VARIOUS_EVENTS: imageSource =R.drawable.all_cats; break;
        case WLConstants.CATEGORY_ALL_FOOD_DRINK: imageSource =R.drawable.restaurants; break;
        return imageSource;
    public void onItemClick(AdapterView<?> adp, View view, int item, long arg3) {

        try {
            if("".equals(sc.getSearchLocation()) && (!(Util.locationFound(sc.getGeoLocation()) && sc.isUK()))){
                UIFactory.displayAlert(new AlertDialog.Builder(HomeBrowse.this), "Error", "Please provide location");
                ResultWrapper wrap = (ResultWrapper)view.getTag();
        } catch (Throwable e) {
            Log.e(TAG, e.getMessage());
            Util.handleError(HomeBrowse.this, HomeBrowse.class, e.getMessage());
            //UIFactory.displayAlert(new AlertDialog.Builder(this), "Error", e.getMessage());
    private void applyListener(){

    private final void goSearch(){
          try {
              Intent mainIntent = new Intent(HomeBrowse.this,SearchResults.class); 
        } catch (Throwable e) {
            Log.e(TAG, e.getMessage());
            Util.handleError(HomeBrowse.this, HomeBrowse.class, e.getMessage());

    public OnClickListener onclickListener = new OnClickListener(){ 
        // @Override 
        public void onClick(View aView) {
             try {
                int componentId =aView.getId();
                     Intent intent = new Intent(HomeBrowse.this,TimeLocationSettings.class);
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
                Util.handleError(HomeBrowse.this, HomeBrowse.class, e.getMessage());


  private void configComponents(){
      String titleStr,location = "";
      String dateCrtStr = Util.getDateCritieraStr(sc.getDateCriteria());
      titleStr= dateCrtStr;
          location = sc.getSearchLocation();
      }else if(sc.isNearMe()){
          location="Near me";
          location = "Postcode or town";
      titleStr = titleStr + " - "+ location;
      changeLink.setTypeface(Typeface.DEFAULT, Typeface.BOLD);

  public class BrowseRow {

        private String name = "";
        private String image = "";
        private String categoryIds="0";
        private String subCategoryIds="0";
        private int searchType=1;

  private Runnable returnRes = new Runnable() {
        public void run() {
            try {
                browseTitle = (TextView)findViewById(;
                changeLink = (TextView)findViewById(;
                changeLink.setText(Html.fromHtml("<a href='#'>Change</a>"));
                adapter=new BrowseAdapter();
                fillResultRows(jsonArray, adapter);
                if(jsonArray == null){
                    UIFactory.displayAlert(new AlertDialog.Builder(HomeBrowse.this), "Error", "Error Loading categories");
            } catch (Throwable e) {

Asked by: Miller657 | Posted: 25-01-2022

Answer 1

Not necessarily everything, because

The default implementation takes care of most of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState(Bundle)).


but if you override, you have to handle entire state by yourself.

Answered by: Melanie417 | Posted: 26-02-2022

Answer 2

You should be saving everything that describes the view's state that isn't saved elsewhere.

Save where the user is in a EditText, what value the EditText has, what dialog is currently displayed, etc. Your application should be able to reconstruct the exact state it was in from the bundle returned to in when it is paused by the user leaving the application and returning to it.

Answered by: Kellan590 | Posted: 26-02-2022

Similar questions

android - Static variables can't be saved in onSaveInstanceState?

Consider following code, it saves static variable: mMyArray in onSaveInstanceState and restore it in onRestoreInstanceState, however I found it can't save the int array at all. I tried primative type value (int), it can save/restore primative type value. public class StaticVarActivity extends Activity { private static final String TAG = "StaticVarActivity"; private static int[] mMyArray = { 1, 1 }...

android - Should onSaveInstanceState save the "enabledness" of the views?

I have a preferences activity where I can change the language and the theme of my application. From there I return to the previous activity via the Back key, and I want to recreate the activity. I've managed to do that by reinitializing the layout in onResume and also calling onRestoreInstanceState from there. All the views are restored properly, with checkboxes checked if needed, edittex...

android - How to save an instance of a custom class in onSaveInstanceState?

I created an instance of a custom class RestaurantList to hold my data (a list of restaurant data received from a web service as json data). How can I save it in onSaveInstanceState?

android - Question on Application Lifecycle and onSaveInstanceState

My application interacts with the Browser in a couple of use cases: First Case: Start MyApplication ActivityA from launcher. Start MyApplication ActivityB using startActivityForResult (ActivityA's onSaveInstanceState is called). Start Browser using startActivity (ActivityB's onSaveInstanceState is called). Close browser or press Back. ActivityB is restored from the saved...

java - Android Notepadv3 tutorial - Is saveState() in onSaveInstanceState really necessary?

I am only a beginner to Android, but I have noticed a number of things that seem a little strange in the third notepad tutorial: The tutorial explicitly states that you need to call saveState from BOTH onSaveInstanceState and onPause. Is this really necessary? It seems to me from reading the process life-cycle documentation that onPause will always be called before the Activity is killed, regardless of whethe...

android - Question about activity lifecycle: onNewIntent / onSaveInstanceState

I have ActivityLanding which calls an activity called ActivityFolder. In the intent I used putExtra("folderId", "...") (I know folderId is not the best example) I can store that to a variable and use it just fine but if eventually my activity gets killed to save memory I may lose the folderId. When my activity gets launched again,, will the "extras" from the intent get preserved? Will the code below work fine?...

bluetooth - Keeping threads and connection state in Android app using onSaveInstanceState?

I am developing a multi player game app for the android. One of the participant is acting as the host (the one who created the game instance) and each of the other participants is connecting to the host using bluetooth. My question is as follows, this host has some threads running in order to communicate and holds all the open connections. I've read that my Activities can be destroyed temporary and restored later a...

android - onSaveInstanceState problem while making oAuth request

Here is my scenario: 1) in my activity, user pushes Authorize button. 2) app opens WebView, in which Twitter page is loaded and user is asked to enter login and password and press Allow button. (oAuth implementation, Twitter requires it in order to integrate your app with Twitter) 3) Remote server passes Intent with Token and Secret back to my Activity, and my Activity then gets control back.

onSaveInstanceState when click back button in Android

I have an activity that is called at runtime in an Android App. When the user clicks the back button the Activity is destroyed and I overrode the onSaveInstanceState method to save outState to be retrieved in a second time but onSaveInstanceState is never called when the user clicks the back button. Do you know why this happens?

Android: Saving contents of a listview onSaveInstanceState

Is there an built in way to save the contents of a listView as part of onSaveInstanceState to then restore later? I want the listView to look the same if the user hit the back button and now onCreate is being called again.

Still can't find your answer? Check out these communities...

Android Google Support | Android Community | Android Community (Facebook) | Android