Search code examples
androidbuttonandroid-tabhostback

Android - How to deal with the back button closing my app and restarting on the right tab


Basically I'm trying to 'remember' in my app which tab was last open when the app was exited. So that it opens on that tab when it's next started.

So I have a tabhost as my main activity and in each of the five tab activities I call the method:

private void mSetTab(){
    SharedPreferences myPrefs=this.getSharedPreferences("myPrefs",MODE_WORLD_READABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putInt("tabToggle", X);
}

Where X is 0-4 depending on the tab.

On my mainActivity I have:

tabHost.setCurrentTab(mCheckTab());

Which calls:

private int mCheckTab() 
{
    SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
    int whichTab = myPrefs.getInt("tabToggle",0);

    return whichTab;
}

This all seems to work fine when the Home key is used but when the back button is used to leave the program then it always seems to load 0.

Any ideas how I get around this?

Cheers

Phil


Solution

  • You need to call commit. There is a nice way to do this, since each of the editor methods return an editor in turn:

    SharedPreferences myPrefs =
        this.getSharedPreferences("myPrefs",MODE_WORLD_READABLE);
    myPrefs.edit().putInt("tabToggle", X).commit();
    

    The home key probably appeared to work because your app was not being closed and was still running in the background.