Now you can Subscribe using RSS

Submit your Email

Wednesday

Start Activity for result Example

Vishal Shrestha
When you use StartActivityForResult your current Activity starts a new activity and waits for callbacks when the started activity decides to finish. For instance, You might record a video in the new acitvity and send the location of the recorded video as the result.

Using startActivityForResult

In Activity A-
Intent i = new Intent(this, ActivityB.class);
startActivityForResult(i, 1);
Here, the second parameter is the requestCode, it is required as you may call different activities from activity A, and those activities return their respective results, so when you use onActivityResult(), you can check from which activity you received the result using the requestCode.

Now, in Activity B, you can send data back like this-


Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
And if you don't want to send data back, just don't putExtra in the intent and instead of RESULT_OK, the first parameter will be RESULT_CANCALED in the setResult.

Now, you can receive the result in Activity A by using onActivityResult method-


protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}
If you have any problems using startActivityForResult, do comment or contact me.

Vishal Shrestha / Author & Founder

A developer by profession, a born Adventurer. I mainly do Android but like to get my hands dirty with web development and a little bit of Python. I would't rather go on a Trek than a party and you can find me having a few rounds with the heavy bag to let out the steam ;)

For Business info : My Portfolio Site.

0 comments:

Post a Comment

Coprights @ 2017 | The Code City by Vishal Shrestha Vishal Shrestha