Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save the state of my activity? [duplicate]

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();
            }
        });
        }
}
like image 294
user2192418 Avatar asked Oct 18 '25 17:10

user2192418


1 Answers

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/

like image 103
Bill Mote Avatar answered Oct 20 '25 07:10

Bill Mote



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!