Return data in Android

Android provides a startActivityForResult() method to return data

    The following example shows how to use startActivityForResult(). The specific code of Activity01 is as follows:

Intent intent = new Intent(this,Activity02.class);
startActivityForResult(intent,1);

    In the above sample code, the startActivityForResult() method receives two parameters, the first parameter is the Intent, and the second parameter is the request code, which is used to determine the source of the data.

    Next, add the sample code for data return in Activity02, as shown below:

Intent intent = new Intent();
intent.putExtra("extra_data","Hello Activity01");
setResult(1,intent);
finish();

    In the above code, the function of returning data is implemented. Among them, the setResult() method receives two parameters, the first parameter resultCode result code, generally use 0 or 1; the second parameter is to pass back the Intent with data, and finally call the finish method to destroy the current Activity.

    Since the startActivityForResult() method is used to start Activity02, the onActivityResult() method will be called back on the Activity01 page, which needs to be rewritten in Activity01 to obtain the returned data. The specific code is as follows:

protected void onActivityResult(int requestCode,int resultCode,Intent data){
    super.onActivityResult(requestCode,resultCoda,data);
    if(resultCode==1){
        String data = data.getStringExtra("extra_data");
        Log.i("Activity01",data);
    }
}
    In the above code, the function of obtaining the returned data is implemented. The onActivityResult() method has three parameters. The first parameter, requestCode, represents the request code passed when starting the Activity; the second parameter, resultCode, represents the result code passed in when returning data; the third parameter, data, represents carrying the returned data. Intent.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324891664&siteId=291194637