0

Alright so in my activity i changed my content view from one to another as you can see. so i was wondering how to save the content view that was there last when my activity was closed.

 public class Levels extends Activity{

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    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();
        }
    });
    }
}
Tobrun
  • 18,291
  • 10
  • 66
  • 81
user2192418
  • 49
  • 1
  • 5
  • what do you mean by "save"? You switched your Activity layout, what do you want to save? – Lisa Anne Apr 06 '13 at 22:10
  • Try saving the edit text values and store and recover using Android Shared Preferences http://stackoverflow.com/questions/15837343/android-permanent-memory/15837366#15837366 – Arnaldo Ignacio Gaspar Véjar Apr 06 '13 at 22:12
  • what i mean by save is that when the user clicks on the activity it won't just show them the first content view(activity layout), it will show them whatever content view(activity layout) they were last on. – user2192418 Apr 06 '13 at 22:23

2 Answers2

2

setContentView

You should call this method only once in the Activity lifecycle.

Saving State

Most of the time you will save your models using onSaveInstanceState and restore them using the bundles generated from that method. Activity, Fragment and Views have these kind of methods build in.

Persisting state

If you are required to use the data for a longer period than the current app lifecycle you can use one of the following mechanisms:

  1. SharedPreferences
  2. SQL-lite DB
  3. File I/O
Tobrun
  • 18,291
  • 10
  • 66
  • 81
0
  1. Create a variable that has the type of R.layout.levels. Assuming R.layout.levels is a RelativeLayout: RelativeLayout rl;

  2. Initialize it like this: rl = (RelativeLayout) getLayoutInflater().inflate(R.layout.levels,null);

  3. setContentView (rl);

If you want to save the variable for when the activity is destroyed you can put it in a custom Application class and retrieve it from there. You find here how to do it at "maintaining global state" : http://www.intridea.com/blog/2011/5/24/how-to-use-application-object-of-android

I don't know if it is good or bad to do this, but it could be a solution for what you're asking.