4

How do I save the way my Activity is so when closed with the backed button and resumed it will be the same way it was when closed.

this is my Activity code:

public class Levels extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setTheme(android.R.style.Theme_NoTitleBar_Fullscreen);
        setContentView(R.layout.levels);

        final EditText anstext1 = (EditText) findViewById(R.id.anstext1);
        Button button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {   
                 String result = anstext1.getText().toString();
                 if(result.equals("they"))
                     setContentView(R.layout.social);
                 else 
                   Toast.makeText(getApplicationContext(), "Wrong", Toast.LENGTH_LONG).show();
            }
        });
        }
}
user2192418
  • 49
  • 1
  • 5
  • If you're referring to saving the instance state, that should already work. If you wish to save the information entered in the EditText when the user for instance presses back (or otherwise finishes the activity), that is dependent upon what the underlying data source is. An API? Local storage? – Paul Lammertsma Apr 03 '13 at 19:13
  • https://stackoverflow.com/a/151940/6600056 – Rob Oct 21 '19 at 14:05

1 Answers1

3

You're going to have to implement onSavedInstanceState() and populate it with the int for the view you're displaying.

Then, in your onCreate(Bundle savedInstanceState) method, you're going to dig the int out of the bundle and set your content view to that.

public class yourActivity extends Activity {

    private static final String KEY_STATE_VIEW_ID = "view_id";
    private int _viewId = R.layout.levels;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (savedInstanceState.containsKey(KEY_STATE_VIEW_ID) {
                _viewId = savedInstanceState.getInt(KEY_STATE_VIEW_ID);
            }
        }
        setContentView(_viewId);
        // in your onClick set viewId to R.layout.social
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putInt(KEY_STATE_VIEW_ID, _viewId);
    }
}

An example can be found here: http://www.how-to-develop-android-apps.com/tag/onsaveinstancestate/

Bill Mote
  • 12,644
  • 7
  • 58
  • 82