tags:

views:

33

answers:

1

Salam

i just started working on android(beginner). Im stuck in the activity state complexity. I created two activitys(activity1 and activity2). wen i move from the activity1 to 2 and then back to activity1 using a button(back of activity)the values(states) of the views are not restored. here is the code..

ACTIVITY1

public class activity1 extends Activity implements OnClickListener {

    String txt;
    EditText etxt;
    TextView tv;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            Toast.makeText(this, "onCreate() : " , Toast.LENGTH_LONG).show();
        }

        setContentView(R.layout.main);
        Button btn_cont = (Button)findViewById(R.id.btn);
        etxt = (EditText)findViewById(R.id.etxt);
        tv = (TextView) findViewById(R.id.tv);
        btn_cont.setOnClickListener(this);
        tv = (TextView) findViewById(R.id.tv);
    }

    @Override
    public void onClick(View click) {
        txt = etxt.getText().toString();
        Intent intent = new Intent(this, Activity2.class);
        startActivity(intent);
        tv.setText(txt);
    }
    public void onSaveInstanceState(Bundle sis){
        sis.putString("ist arg", "sec arg");
        Toast.makeText(this, "ActivitySaveIns", Toast.LENGTH_LONG).show();
        super.onSaveInstanceState(sis);
    }
}

ACTIVITY2

public class Activity2 extends Activity implements OnClickListener{

    Button btn_back;
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.act2);
        btn_back = (Button)findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
    }

    public void onClick(View v) {
        Intent intent2 = new Intent(this,activity1.class);
        startActivity(intent2);

    }
}
A: 

Here is what your doing:

  1. Start Activity1
  2. Start Activity2
  3. Start [another instance of] Activity1

So after you have pressed the 'back' button [you should just let the hardware back button do the job!], you end up with three activities.

If you want to keep a back button like that, instead of creating a new instance just call onBackButtonPressed() which will close the current Activity (and take you back to the original one).

antonyt
thanx alot that was so helpful. . i used the onresume() to the state of the activity1.
Kamal
Please accept the answer (the tick mark) if it solved your problem!
antonyt
does it mean that i hav to do all the coding in the onresume() to restore the views values??
Kamal
If you are going back to the same activity (i.e. when you press back), then you don't have to do any work to restore the values. If you want to pass values back, look into startActivityForResult(). http://developer.android.com/reference/android/app/Activity.html#StartingActivities
antonyt