Monday, 10 April 2017

How to manage `startActivityForResult` on Android?


startActivityForResult functinality working as...

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

In your SecondActivity set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.


For example: In secondActivity if you want to send back data:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);

finish();


If you don't want to return data:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);

finish();


Now in your FirstActivity class write following code for the onActivityResult() method.(override onActivityResult() inbuild method of Activity).

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

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }

}//onActivityResult

No comments:

Post a Comment

Run/install/debug Android applications over Wi-Fi ?

Open Teminal/cmd --------------- Below steps is for Android 10 or lower Step 1 - Connect the device via USB and make sure debugging is work...