user4332856
user4332856

Reputation:

How to send an intent through finish() when going back to previous Activity?

I am making an application where my activities navigation is set up like this

Main Activity <-> Results -> End

My application will be sending data through intents from the Main Activity to the Results Activity where the Results Activity will calculate and display the data. The Results Activity will either return the calculated results back to the Main Activity or determine that the conditions have been met and to start the End Activity. The End Activity will be able to navigate back to Main Activity to start the application over passing no data over.

My problem is I can't figure out how to effectively send the data back to the Main Activity from the Results Activity while having the option to send the data to the End Activity once the conditions have been met. While doing research I found the method startActivityForResult however my dilemma is that my Results Activity may not always return a result back to the Main Activity once the conditions have been met.

Should I use startActivityForResult for the Main Activity and Result Acitivity and start a new activity for End Activity once the condition has been met or would using Shared Preferences be a better option in this situation?

Upvotes: 0

Views: 97

Answers (1)

Robillo
Robillo

Reputation: 212

Check out this link: https://developer.android.com/training/basics/intents/result.html

Instead of calling startActivity(intent), you have to call: startActivityForResult(intent, requestCode (say, =2)) from main activity.

Then in your ResultActivity, you have to all your extras and info within your intent object. Before calling finish(), you have to call setData(requestCode = 2, intent).

Then, in your MainActivity, you have to override the onActivityResult() function and handle the response like:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == 2) {
        // Make sure the request was successful

    }
}

Upvotes: 1

Related Questions