简体   繁体   中英

Maintain Activity State with two Activities

We have and Android App that contains two Activities MainActivity and PageTwo. In the MainActivity we have an EditText widget set to accept number input only and a Button that goes to the next activity with the aid of an Intent. On the second activity PageTwo we have a Button that returns the user to the MainActivity with an Intent. When we enter a value in the EditText field and make the trip from the MainActivity to PageTwo activity and back the value is seemingly erased unless you use the device (emulator) back button. I am trying to maintain the Activity State of this one EditText variable

code snippets

 EditText ETage;
 int vAGE;
 static final String V_AGE = "vAGE"; //KeyValue Pair

@Override
public void onSaveInstanceState(Bundle outState){
    outState.putInt(V_AGE,vAGE);
    super.onSaveInstanceState(outState);
}

//@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
    super.onRestoreInstanceState(savedInstanceState);
    vAGE = savedInstanceState.getInt(V_AGE);
    ETage.setText(String.valueOf(vAGE));
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //if(savedInstanceState != null){
        //vAGE = savedInstanceState.getChar(V_AGE);
    //}
    setContentView(R.layout.activity_main);

  ETage = (EditText)findViewById(R.id.editTextAge); 

if you want to go back to previous Activity why you are calling intent? just simply write onBackPressed(); inside onClick

Example

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        onBackPressed();
    }
});

or if you really wanted to use intent you can always use finish() .

Example

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        Intent i = new Intent(PageTwo.this, MainActivity.class);            
        startActivity(i);
        finish();
    }
});

In PageTwo second activity don't return to MainActivity with an intent. Simply, do following in button click:

super.onBackPressed(); // this instead of intent to start MainActivity

From what I understand from your question you can do like this in second page:

@Override
public void onBackPressed() {
    super.onBackPressed();

Intent intent = new   Intent(SecondActivity.this,MainActivity.class);
        startActivity(intent);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM