androidandroid-activityonactivityresult

Android: how to make an activity return results to the activity which calls it?


I have a Location activity that can be called from many activities, such as Sign up and Order. In the Location activity the user enters his location, so the activity Location will return this new location to that activity which called it.

So when the Sign up activity calls the Location activity, it has to return the data to the Sign up activity. Another time the Order activity will do the same thing.

Note

I know you will tell me that I should post the code, but I am not asking you to give me the code; I just want some tips, links or good threads.


Solution

  • In order to start an activity which should return result to the calling activity, you should do something like below. You should pass the requestcode as shown below in order to identify that you got the result from the activity you started.

    startActivityForResult(new Intent(“YourFullyQualifiedClassName”),requestCode);
    

    In the activity you can make use of setData() to return result.

    Intent data = new Intent();
    String text = "Result to be returned...."
    //---set the data to pass back---
    data.setData(Uri.parse(text));
    setResult(RESULT_OK, data);
    //---close the activity---
    finish();
    

    So then again in the first activity you write the below code in onActivityResult()

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == request_Code) {
            if (resultCode == RESULT_OK) {
                String returnedResult = data.getData().toString();
                // OR
                // String returnedResult = data.getDataString();
            }
        }
    }
    

    EDIT based on your comment: If you want to return three strings, then follow this by making use of key/value pairs with intent instead of using Uri.

    Intent data = new Intent();
    data.putExtra("streetkey","streetname");
    data.putExtra("citykey","cityname");
    data.putExtra("homekey","homename");
    setResult(RESULT_OK,data);
    finish();
    

    Get them in onActivityResult like below:

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == request_Code) {
            if (resultCode == RESULT_OK) {
                String street = data.getStringExtra("streetkey");
                String city = data.getStringExtra("citykey");
                String home = data.getStringExtra("homekey");
            }
        }
    }