Search code examples
androidandroid-activityactivity-finish

Proper way to close/finish Activity in Android


My app starts up at Activity A which contains a ListView. The ListView can have items added to it if the user hits "Add" button and goes to Activity B.

In Activity B they fill out some forms and hit "OK" button which takes them back to Activity A where the new item is added to the ListView.

I have a finish() method after going from B to A -- but NOT the other way around.

So if you hit back three times after adding three items. It will just repeat the ListView (Activity A) over 3 times -- less one item that was added.

What is the best way in doing this? I can't put a finish method on the "Add" Button (going from A to B) because if you are in Activity B, it will close the app instead of taking you back to A -- which I do not want. That is, if the user changes his mind and doesn't want to "Add new item" by hitting "OK" while in B. Is a manual Back button the only answer?


Solution

  • Start Activity B by using startActivityForResult() and finish activity B after filling the form.

    EDIT

    When you startActivityForResult(), you pass 2 parameters, namely intent and requestcode. After you are finished with the new activity(in your case Activity B) you use a function setResult(RESULT_OK) to signify that the operation in Activity B was successful and then you call finish(). After the call to finish() the Activity B will return to Activity A and will call onActivityResult(int requestCode, int resultCode, Intent data). The parameter requestcode helps in identifying which particular activity/request has returned.

    Hope this explanation helps you.