Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass values between Activities on Android?

Tags:

This is the navigation of my application:

Activity1 calls Activity2Activity2.finish(), call Activity3Activity3.finish()

When Activity3 finishes, it calls the onResume method of Activity1. Now how can I pass a value from Activity3 to Activity1?

like image 349
magemello Avatar asked May 02 '11 01:05

magemello


People also ask

How can we pass data from one activity to another using Android Intent?

putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair. Add the below code in onClick() method. intent. putExtra("full_name", fullName);

How can I pass multiple EditText values to another activity in Android?

You need put them in Extras (putExtras) and then pass from the current activity to the other one. You need capture your EditText value as String and then putExtra with Key - one each for your need and then retrieve them in the second activity.

How do you pass data between activities using Intent?

Intent supports three ways to pass data: Direct: put our data into intents directly. Bundle: create a bundle and set the data here. Parcelable: It is a way of “serializing” our object.


2 Answers

Umesh shows a good technique but I think you want the opposite direction.

Step 1

When starting Activity 2 and 3, use startActivityForResult. This allows you handle the result in the calling activity.

startActivityForResult(MY_REQUEST_ID); 

Step 2

In Activities 2 and 3, call setResult(int, Intent) to return a value:

Intent resultData = new Intent(); resultData.putExtra("valueName", "valueData"); setResult(Activity.RESULT_OK, resultData); finish(); 

Step 3

In your calling activty, implement onActivityResult and get the data:

protected void onActivityResult(int requestCode, int resultCode,           Intent data) {       if (requestCode == MY_REQUEST_ID) {           if (resultCode == RESULT_OK) {             String myValue = data.getStringExtra("valueName");              // use 'myValue' return value here           }       } } 

Edit:

Technique #2

Yes, you can also use global application state by adding a class to your application that extends Application, see this StackOverflow answer

like image 53
Mike Marshall Avatar answered Sep 23 '22 22:09

Mike Marshall


Use the session id to the signout activity in the intent you're using to start the activity:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class); intent.putExtra("EXTRA_SESSION_ID", sessionId); startActivity(intent) 

See this tutorial.

like image 25
Umesh K Avatar answered Sep 21 '22 22:09

Umesh K