Return results from intent
The startActivity () method calls another activity, but no result is returned to the current activity. To return data from an activity, you must use the startActivityForResult () method.
Click here to get the complete code ~
1. Use the project created in the previous article to add text boxes and buttons to the secondactivity. xml file. The Code is as follows:
2. Add the onClick () method to the SecondActivity. java file. The Code is as follows:
Public void onClick (View v) {Intent data = new Intent (); EditText txt_username = (EditText) findViewById(R.id.txt _ username); // use setData () method: use an Intent object to return data. setData (Uri. parse (txt_username.getText (). toString (); // setResult () method to set the result code and setResult (RESULT_ OK, data) returned to the call activity; // disable Activityfinish ();}
3. Add the following code to the MainActivity. java file:
In The onClick () method:
StartActivityForResult (new Intent (this, SecondActivity. class), request_Code); // This method calls an activity and waits for the result returned from this activity: Incoming Intent object and request code (only an integer to identify the activity being called)
OnActivityResult () method defined by myself:
// When an activity returns, you must call your own onActivityResult () method public void onActivityResult (int requestCode, int resultCode, Intent data) {if (requestCode = request_Code) {// check the request code if (resultCode = RESULT_ OK) {// check the result code Toast. makeText (this, data. getData (). toString (), Toast. LENGTH_SHORT ). show ();}}}
4. Running:
Click:
Enter the name and click OK:
Summary:
1. Call the onstartActivityForResult () method and set the request code;
2. In the called activity, return data through the Intent object and set the result code (setData () method and setResult () method );
3. In the call activity, define the onActivityResult () method, verify the Request Code and result code, and then perform other processing.