In Android we can pass data from one activity to another via Intent using startActivity(). The syntax for this is shown below :
1 2 3 |
Intent in = new Intent(MainActivity.this, SecondActivity.class); in.putExtra("message",message); startActivity(in); |
Similarly we can get data from our other activity that is opened by an activity like SecondActivity from MainActivity and we need some message from SecondActivity back again to MainActivity so for this we need startActivityForResult(). Below is syntax of startActivityForResult that is in MainActivity.
1 2 |
Intent in = new Intent(MainActivity.this, SecondActivity.class); startActivityForResult(in, 2);//2 is request code |
Here 2 is request code for this activity and make sure no two activity have same request code.
Now in SecondActivity we send back result via intent. While sending back intent we have to setResult() :
1 2 3 |
Intent intent = new Intent(); intent.putExtra("message",message);//Put Message to pass over intent setResult(RESULT_OK,intent);//Set result OK |
1 2 |
Intent intent = new Intent(); setResult(RESULT_CANCELED, intent);//For cancel button set result CANCEl |
Finally in MainActivity class we have to get result in onActivityResult() method and check the request code and result code and do according to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Call Back method to get the Message form other Activity @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // check if the request code is same as what is passed here it is IntentId if (requestCode == IntentId) { if (resultCode == RESULT_OK) { //If result code is OK then get String extra and set message String message = data.getStringExtra("message"); resultMessage.setText(message); } if (resultCode == RESULT_CANCELED) //When result is cancelled display toast Toast.makeText(MainActivity.this, "Activity cancelled.", Toast.LENGTH_SHORT).show(); } } |
In this tutorial, we are going to learn how to get result back from an activity using startActivityForResult.
1. Create a new project in Android Studio by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Open res=>values=>strings file and add the following strings.
1 2 3 4 5 6 7 8 9 10 |
<resources> <string name="app_name">StartActivityForResult Demo</string> <string name="resultMessage">Result Message</string> <string name="getResult">Get Result</string> <string name="enterMessage">Enter Your Message</string> <string name="seciindActivityTitle">Message enetered here will be displayed in MainActivity</string> <string name="cancel">Cancel</string> <string name="submit">Submit</string> <string name="secondActivity">Second Activity</string> </resources> |
3. Create a layout xml file naming activity_main.xml and add the following code. In this i had taken one TextView that will display return message from second activity and a Button that will open second activity.
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 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <!-- Message from Second Activity will be displayed here --> <TextView android:id="@+id/resultMessage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:text="@string/resultMessage" android:textColor="#000000" android:textSize="17sp" /> <!-- This will open second activity --> <Button android:id="@+id/secondActivityBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="3dp" android:ems="12" android:text="@string/getResult" /> </LinearLayout> |
4. Now create a new xml file naming second_activity.xml and add the following code. In this we are having an EditText for take user input and a two Button one for Cancel and one for Submit.
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 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="5dp"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="10dp" android:text="@string/seciindActivityTitle" android:textColor="#000000" android:textSize="17sp" /> <!-- Enter your message --> <EditText android:id="@+id/inputMessage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:hint="@string/enterMessage" android:padding="10dp" android:textColor="#000000" android:textColorHint="#d3d3d3" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:orientation="horizontal"> <Button android:id="@+id/cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="5dp" android:layout_weight="1" android:text="@string/cancel" /> <Button android:id="@+id/submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_weight="1" android:text="@string/submit" /> </LinearLayout> </LinearLayout> |
5. Open your MainActivity.java and the following code. In this code i have used all steps mentioned at starting.
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 |
package com.androidstartactivityforresult_demo; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { public static final int IntentId =1; //Intent Request Code private static TextView resultMessage; private static Button getMessageBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); resultMessage = (TextView)findViewById(R.id.resultMessage); getMessageBtn = (Button)findViewById(R.id.secondActivityBtn); getMessageBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Open second activity with request code Intent in = new Intent(MainActivity.this, SecondActivity.class); startActivityForResult(in, IntentId); } }); } // Call Back method to get the Message form other Activity @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // check if the request code is same as what is passed here it is IntentId if (requestCode == IntentId) { if (resultCode == RESULT_OK) { //If result code is OK then get String extra and set message String message = data.getStringExtra("message"); resultMessage.setText(message); } if (resultCode == RESULT_CANCELED) //When result is cancelled display toast Toast.makeText(MainActivity.this, "Activity cancelled.", Toast.LENGTH_SHORT).show(); } } } |
6. Now create a new java file naming SecondActivity.java and add the following code. In this class i am returning message on Submit button click and cancelling activity on Cancel button click.
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 |
package com.androidstartactivityforresult_demo; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * Created by SONU on 25/09/15. */ public class SecondActivity extends AppCompatActivity implements OnClickListener{ private static EditText inputMessage; private static Button cancel, submit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activity); inputMessage = (EditText)findViewById(R.id.inputMessage); cancel = (Button)findViewById(R.id.cancel); submit = (Button)findViewById(R.id.submit); cancel.setOnClickListener(this); submit.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.submit: String message=inputMessage.getText().toString(); if(message.length()!=0 && !message.equals("")) { Intent intent = new Intent(); intent.putExtra("message",message);//Put Message to pass over intent setResult(RESULT_OK,intent);//Set result OK finish();//finish activity } else Toast.makeText(SecondActivity.this, "Please enter a message.", Toast.LENGTH_SHORT).show(); break; case R.id.cancel: Intent intent = new Intent(); setResult(RESULT_CANCELED, intent);//For cancel button set result CANCEl finish();//finish activity break; } } } |
7. Finally come to your Manifest file and add your SecondActivity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidstartactivityforresult_demo" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SecondActivity" android:label="@string/secondActivity"></activity> </application> </manifest> |
8. Now, you are all done, run your app and you will get the output as shown in video.
Thanks.
Subscribe to us and get the latest news.