Intents are mainly used for communication between 2-activities or to pass data between them. Whenever we start a new Activity using Intent, that Intent can also return some result to our older Activity from newly created Activity. This process is called receiving intent result.
- Many a times we might have various operations to be carried out from our Activity. Adding all operations in same activity will take the charm of User-Interface. For that we might have multiple Activities computing the operations separately and sending back result to the main Activity.
- Say for e.g. you start the Numeric Key-pad to call a person, in order find number of that person you might invoke contact book. On selecting the contact you’ll receive the contact details as a result back to your Numeric Key-pad.
- Another Intent Result Example : while using any App you want to capture a photograph, the application invokes the default Camera App. You click a picture & that App receives an image as intent result from the Camera App.
Source Code : Intent Result Data.zip
Now Let us work on Project : (Refer – Configuring Existing AndroidStudioProject) Intent Result Data which you might have downloaded from above or you can follow the scripts below by copying it to implement in your Project. To launch Downloaded project, Extract the zip, copy it into AndroidStudioProjects. Now from Android Studio click open Existing Android Studio Project and select the path to extracted file we just copied in AndroidStudioProjects directory. If Sync SDK path prompt comes just click OK and you are ready to work. If still you get error check for AndroidStudioProjects/IntentResultData/app/build.gradle , it will contain different SDK Version. Change it to SDK Version which you have.
Over here we will work on 2 main files :
- MainActivity1.java which will invoke MainActivity2.java & waits till MainActivity2.java responds either with Success or Failure as Intent Result.
- MainActivity2.java which is invoked by MainActivity1.java, sends Intent Result back to MainActivity1.java, when user clicks the Button.
MainActivity1.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
package com.nestedif.intentresultdata; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity1 extends Activity { // This is the Request Code which we pass to MainActivity2 and expect same as a result int REQ_CODE = 1; // Name Value Pair Concept public static String TAG_MESSAGE = "tg_message"; String received_message = ""; TextView tv ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main1); tv = (TextView)findViewById(R.id.textView2); } // This method will be called on button click public void run(View v) { // Declaring Intent object Intent i = new Intent(this,MainActivity2.class); // Passing intent with Request code = 1 (We expect same as Result Code to demonstrate success ) startActivityForResult(i, REQ_CODE); // This Request Code is helpful to identify the originating Activity for result, when we have multiple Activities Responding Intent Result } // This method will be called on Receiving Response from MainActivity2 public void onActivityResult(int requestCode , int resultCode , Intent data) { // On Comparing if we get both values same i.e. we have an expected result else we can show an Error Message if(requestCode == resultCode ) { // This receives Data from MainActivity2 and saves it in string variable received_message = "Received Data : " + data.getStringExtra(TAG_MESSAGE); // Setting TextView with Received Data tv.setText(received_message); // Simple Toast Message to display Success with received message Toast.makeText(this, received_message , Toast.LENGTH_SHORT).show(); } else { // Simple Toast Message to display Failure Toast.makeText(this, "Error Message" , Toast.LENGTH_SHORT).show(); } } } |
Explaining above Code :
- Line 13 We have declared integer variable REQ_CODE which will help us identify incoming intent result belongs to which Activity in case we have multiple activities. We have declared its value 1, which means that only Activity returning same REQ_CODE for intent result will be kept rest will be ignored.
- Line 16 We have declared name-value pair TAG_MESSAGE which will be used for exchanging data using Intent. And we have made it static since we will also need to use it in MainActivity2.java.
- Line 34 Whenever we click our button this method will be invoked.
- Line 37 We have declared an Explicit Intent passing context & MainActivity2.class as 2 parameters.
- Line 40 startActivityFor Result() starts MainActivity2 with intention of receiving intent result. At this point our MainActivity1 will be sent to background & MainActivity2 will be started & brought in front.
- Line 48 Whenever our MainActivity2 will send response onActivityResult() will be invoked with 3 parameters passed by MainActivity2, viz : requestCode & resultCode – to confirm that proper intent result is received at MainActivity1 & Intent data which is the data sent from MainActivity2 in form of intent result.
- Line 51 We compare requestCode with resultCode if both match then we assume successful reception of intent result else we give error message.
- Line 54 using data.getStringExtra(TAG_MESSAGE) we extract the message from intent result sent by MainActivity2.
MainActivity2.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package com.nestedif.intentresultdata; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity2 extends Activity { EditText et1 ; int REQ_CODE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); et1 = (EditText)findViewById(R.id.editText1); } public void run(View v) { // Storing Value of EditText into String Variable e1 String e1 = et1.getText().toString(); // Creating Intent object Intent ri = new Intent(); // Attaching e1 String value with ri Intent object ri.putExtra(MainActivity1.TAG_MESSAGE, e1); // Setting Result Code (REQ_CODE = 1 means success in our case, yet we can define any values depending on Number of Activities responding to Intent Result) setResult(REQ_CODE, ri); // Closing this Activity finish(); } } |
Explaining above Code :
- Line 24 After filling the EditText we submit it by clicking send button, our run method will be called which deals with sending intent result back to MainActivity1.
- Line 32 We have declared intent using which we will send back intent result to MainActivity1. ( See that we haven’t passed any parameters to this intent )
- Line 35 Using the above intent instance we attach data of our EditText using method putExtra().
- Line 38 We send intent result back to MainActivity1 with resultCode REQ_CODE = 1 i.e. success using setResult().
activity_main1.xml : Layout file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingTop="5dp" android:paddingLeft="5dp" android:paddingRight="5dp" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="20dp" android:text="In response from the second activity you will receive data below the button" android:textSize="20sp" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click to Go Ahead" android:onClick="run" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="20dp" android:text="" android:textAppearance="?android:attr/textAppearanceLarge" /> </LinearLayout> |
- Inside our activity_main1.xml we have added 1st TextView to display static info., 2nd Button to start MainActivity2 & 3rd TextView to display received intent result.
activity_main2.xml : Layout file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingTop="5dp" android:paddingLeft="5dp" android:paddingRight="5dp" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="The data entered in this text box will be sent to previous activity" android:textSize="20sp"/> <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="15dp" android:ems="10" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" android:onClick="run"/> </LinearLayout> |
- Inside our activity_main2.xml we have simply added 1-EditText to collected message from user & 1-Button to send intent result back to MainActivity1.
Final Output :
Connect with us