views:

187

answers:

2

Say I have 2 activities (ActivityOne and ActivityTwo). How would I call ActivityTwo from ActivityOne? Then how would I return to ActivityOne from ActivityTwo? For example, I have a listview with all the contacts on the host phone. When I tap on a contact, another activity shows information and allows editing of that contact. Then I could hit the back button, and I would go back to the exact state that ActivityOne was in before I called ActivityTwo. I was thinking an Intent object, but I am not sure. Could someone post some code?

+3  A: 

In your first activity (AcitvityOne) you could call

Intent intent = new Intent(this, ActivityTwo.class);
startActivityForResult(intent, CODE);

Then you can override

public void onActivityResult(int reqCode, int resultCode, Intent data) {

to receive the result of this activity

Roflcoptr
If you do not need to get the results of `ActivityTwo`, you can just use `startActivity()` and skip implementing `onActivityResult()`.
CommonsWare
+2  A: 

In your example, it seems like you will want to pass data between Activity One and Activity Two (namely, the reference of the contact you want to edit), so you should use a Bundle with your intent in Activity One.

    Intent myIntent = new Intent(this, ActivityTwo.class);
    myIntent.putExtra("CONTACT", position);
    this.startActivity(myIntent);

"CONTACT" is a key and position is a value (position would have been defined before, it could be whatever you want it to be, for example an integer. The way you retrieve it is slightly different based on what type it is, note the getInt() in Activity Two code below).

And in Activity Two, in onCreate()

Bundle extras = getIntent().getExtras();
    if (extras != null) {
        contact = extras.getInt("CONTACT");
        /**Do what you want with the integer value you have retrieved**/
    }

As for your other question, the back button removes the current Activity from the top of the tasks stack and therefore, you return to the previous Activity, normally in exactly the same state as you have left it.

However, if the phone is running low on memory, Android might kill off a process or Activity so it is possible in theory that your previous Activity will not show in exactly the same state as you have left it. If you have any important data, you should save it before launching Activity Two. If you just want to return to Activity One in the same state for user friendliness, then it's fine to rely on the back button.

FreewheelNat