857

How can I send data from one activity (intent) to another?

I use this code to send data:

Intent i=new Intent(context,SendMessage.class);
i.putExtra("id", user.getUserAccountId()+"");
i.putExtra("name", user.getUserFullName());
context.startActivity(i);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adham
  • 63,550
  • 98
  • 229
  • 344
  • 91
    Java side note: It is never a good idea to "stringify" integer like that (especially for example purposes), and unfortunately it is frequently considered a good, quick way to convert int to string in java: `user.getUserAccountId()+""`, as this would create unnecessary objects to be collected. Consider using `String.valueOf(user.getUserAccountId)`, or `Integer.toString(user.getUserAccountId)` instead. – pkk Jul 09 '13 at 07:47
  • 6
    @Andrew S Is this not the web? This is the number one result for "get data from intent" – McGuile Jun 20 '18 at 22:45
  • @AndrewS I agree with McGuile. Also, this question was posted a while ago so the answer probably wasn't as easy to find back then. And if a similar question hadn't been posted to SO yet, then it was a valid post. – 0xCursor Sep 02 '18 at 02:46

18 Answers18

1366

First, get the intent which has started your activity using the getIntent() method:

Intent intent = getIntent();

If your extra data is represented as strings, then you can use intent.getStringExtra(String name) method. In your case:

String id = intent.getStringExtra("id");
String name = intent.getStringExtra("name");
Malcolm
  • 41,014
  • 11
  • 68
  • 91
  • 10
    from where to can i all this method ?? – Adham Nov 20 '10 at 17:06
  • 54
    @adham: If you are in an activity, from within onCreate, you call `getIntent().getStringExtra("id");` to get the id string – ccheneson Nov 20 '10 at 17:08
  • 1
    You can get the intent which started your activity by calling `getIntent()` method. I've updated the answer. – Malcolm Nov 20 '10 at 17:09
  • What if the data is an image? – Sauron Jun 14 '14 at 02:53
  • @Eatlon Then it all depends on how the image is represented. For example, if it's an array of bytes, you'll have to call `intent.getByteArrayExtra("image")`. – Malcolm Jun 14 '14 at 04:24
  • @Malcolm I'm using Picasso from square pulls the image and places it straight from its http address. Will the change the configuration at all? – Sauron Jun 14 '14 at 14:19
  • 2
    @Eatlon If you have a problem with a specific library, you should create a separate question about that. – Malcolm Jun 14 '14 at 14:42
  • @Malcolm I got it to work, just dumped Picasso into the next class started by the activity and image appears very quickly, no problems. – Sauron Jun 14 '14 at 17:17
  • 3
    @MelColm what is the difference between getExtra().getString and getStringExtra()? – Amit Tripathi Feb 07 '15 at 14:46
  • 1
    @Amit None, the latter is just a shortcut to the former. – Malcolm Feb 07 '15 at 16:00
  • @WarungNasi49 There is the `hasExtra` method, but I'd rather null-check the returned value as it's more robust. – Malcolm Jan 04 '17 at 14:31
  • can i get an array list the similar way?? – Shreyas Sanil Aug 16 '17 at 13:22
  • @ShreyasSanil Sure. The method you need to call depends on what it is an array list of. For example, there is a method `getStringArrayListExtra` for `ArrayList`. – Malcolm Aug 16 '17 at 13:24
  • What if some other activity also starts and puts extra? How do I identify which activity has started the activity and get intent of that activity only? – MONU KUMAR Jul 04 '18 at 07:01
  • @MONUKUMAR `getIntent` always returns the intent that started this activity. All other intents either start new activities or arrive in `onNewIntent` of the current. – Malcolm Jul 04 '18 at 09:20
209

In the receiving activity

Bundle extras = getIntent().getExtras(); 
String userName;

if (extras != null) {
    userName = extras.getString("name");
    // and get whatever type user account id is
}
NickT
  • 23,844
  • 11
  • 78
  • 121
  • 7
    Why is this preferable over `getStringExtra?` – IgorGanapolsky Oct 02 '15 at 15:25
  • 7
    My guess is: if the extras can be `null`, the whole extras fetch can be skipped. By using `getStringExtra`, you basically change it to a series of `if(extras != null) { return extras.getString(name) }`. One for each `getStringExtra` you call. This option will check for `null` once and if so, it won't bother reading the `Bundle` at all. Besides that, `getStringExtra` will probably keep asking `getExtras` internally each time as well. So you simply have more calls to functions. – Daniël Sonck Feb 21 '16 at 01:02
45
//  How to send value using intent from one class to another class
//  class A(which will send data)
    Intent theIntent = new Intent(this, B.class);
    theIntent.putExtra("name", john);
    startActivity(theIntent);
//  How to get these values in another class
//  Class B
    Intent i= getIntent();
    i.getStringExtra("name");
//  if you log here i than you will get the value of i i.e. john
Sumit Sharma
  • 1,847
  • 1
  • 22
  • 25
36

Add-up

Set Data

String value = "Hello World!";
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
intent.putExtra("sample_name", value);
startActivity(intent);

Get Data

String value;
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    value = bundle.getString("sample_name");
}
kenju
  • 5,866
  • 1
  • 41
  • 41
18

Instead of initializing another new Intent to receive the data, just do this:

String id = getIntent().getStringExtra("id");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
r_allela
  • 792
  • 11
  • 23
15

Put data by intent:

Intent intent = new Intent(mContext, HomeWorkReportActivity.class);
intent.putExtra("subjectName", "Maths");
intent.putExtra("instituteId", 22);
mContext.startActivity(intent);

Get data by intent:

String subName = getIntent().getStringExtra("subjectName");
int insId = getIntent().getIntExtra("instituteId", 0);

If we use an integer value for the intent, we must set the second parameter to 0 in getIntent().getIntExtra("instituteId", 0). Otherwise, we do not use 0, and Android gives me an error.

ib.
  • 27,830
  • 11
  • 80
  • 100
11

If used in a FragmentActivity, try this:

The first page extends FragmentActivity

Intent Tabdetail = new Intent(getApplicationContext(), ReceivePage.class);
Tabdetail.putExtra("Marker", marker.getTitle().toString());
startActivity(Tabdetail);

In the fragment, you just need to call getActivity() first,

The second page extends Fragment:

String receive = getActivity().getIntent().getExtras().getString("name");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bundit Ng
  • 119
  • 1
  • 5
  • 1
    Also you could use getStringExtra("name") instead of getExtras().getString("name") – Plot Dec 04 '14 at 18:06
8

If you are trying to get extra data in fragments then you can try using:

Place data using:

Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER);

Get data using:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


  getArguments().getInt(ARG_SECTION_NUMBER);
  getArguments().getString(ARG_SECTION_STRING);
  getArguments().getBoolean(ARG_SECTION_BOOL);
  getArguments().getChar(ARG_SECTION_CHAR);
  getArguments().getByte(ARG_SECTION_DATA);

}
Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42
DPP
  • 12,716
  • 3
  • 49
  • 46
7

You can get any type of extra data from intent, no matter if it's an object or string or any type of data.

Bundle extra = getIntent().getExtras();

if (extra != null){
    String str1 = (String) extra.get("obj"); // get a object

    String str2 =  extra.getString("string"); //get a string
}

and the Shortest solution is:

Boolean isGranted = getIntent().getBooleanExtra("tag", false);
shobhan
  • 1,460
  • 2
  • 14
  • 28
Sheikh Hasib
  • 7,423
  • 2
  • 25
  • 37
7

Kotlin

First Activity

val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)

Second Activity

val value = getIntent().getStringExtra("key")

Suggestion

Always put keys in constant file for more managed way.

companion object {
    val PUT_EXTRA_USER = "PUT_EXTRA_USER"
}
Community
  • 1
  • 1
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
2

Just a suggestion:

Instead of using "id" or "name" in your i.putExtra("id".....), I would suggest, when it makes sense, using the current standard fields that can be used with putExtra(), i.e. Intent.EXTRA_something.

A full list can be found at Intent (Android Developers).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
eva
  • 59
  • 3
2

We can do it by simple means:

In FirstActivity:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);

In SecondActivity:

    try {
        Intent intent = getIntent();

        String uid = intent.getStringExtra("uid");
        String pwd = intent.getStringExtra("pwd");

    } catch (Exception e) {
        e.printStackTrace();
        Log.e("getStringExtra_EX", e + "");
    }
vss
  • 1,093
  • 1
  • 20
  • 33
2

Pass the intent with value on First Activity:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("uid", uid.toString());
intent.putExtra("pwd", pwd.toString());
startActivity(intent);

Receive intent on second Activity;-

Intent intent = getIntent();
String user = intent.getStringExtra("uid");
String pass = intent.getStringExtra("pwd");

We use generally two method in intent to send the value and to get the value. For sending the value we will use intent.putExtra("key", Value); and during receive intent on another activity we will use intent.getStringExtra("key"); to get the intent data as String or use some other available method to get other types of data (Integer, Boolean, etc.). The key may be any keyword to identify the value means that what value you are sharing. Hope it will work for you.

Ruzin
  • 1,645
  • 2
  • 14
  • 14
Pradeep Sheoran
  • 493
  • 6
  • 15
1

You can also do like this
// put value in intent

    Intent in = new Intent(MainActivity.this, Booked.class);
    in.putExtra("filter", "Booked");
    startActivity(in);

// get value from intent

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    String filter = bundle.getString("filter");
Savita Sharma
  • 344
  • 3
  • 9
1

Getting Different Types of Extra from Intent

To access data from Intent you should know two things.

  • KEY
  • DataType of your data.

There are different methods in Intent class to extract different kind of data types. It looks like this

getIntent().XXXX(KEY) or intent.XXX(KEY);


So if you know the datatype of your varibale which you set in otherActivity you can use the respective method.

Example to retrieve String in your Activity from Intent

String profileName = getIntent().getStringExtra("SomeKey");

List of different variants of methods for different dataType

You can see the list of available methods in Official Documentation of Intent.

Rohit Singh
  • 16,950
  • 7
  • 90
  • 88
1

This is for adapter , for activity you just need to change mContext to your Activty name and for fragment you need to change mContext to getActivity()

 public static ArrayList<String> tags_array ;// static array list if you want to pass array data

      public void sendDataBundle(){
            tags_array = new ArrayList();
            tags_array.add("hashtag");//few array data
            tags_array.add("selling");
            tags_array.add("cityname");
            tags_array.add("more");
            tags_array.add("mobile");
            tags_array.add("android");
            tags_array.add("dress");
            Intent su = new Intent(mContext, ViewItemActivity.class);
            Bundle bun1 = new Bundle();
            bun1.putString("product_title","My Product Titile");
            bun1.putString("product_description", "My Product Discription");
            bun1.putString("category", "Product Category");
            bun1.putStringArrayList("hashtag", tags_array);//to pass array list 
            su.putExtras(bun1);
            mContext.startActivity(su);
        }
Android Geek
  • 8,956
  • 2
  • 21
  • 35
0
A class to B class Data Sending 

A class:

Intent in = new Intent(A.this, B.class);
in.putExtra("Name", ""+user.getUserFullName());
startActivity(in);

B class:

String name = getIntent().getStringExtra("Name");
-1

In Kotlin and Jetpack Compose, use this:

val context = LocalContext.current
val intent = Intent(context, Activity2::class.java)
intent.putExtra("name", "John")
intent.putExtra("data2","aaaa")
context.startActivity(intent)

and in Activity2:

val intent = intent
val name = intent.getStringExtra("name")
val data2 = intent.getStringExtra("data2")

You can test by writing to the logcat:

`Log.d("A2", "Name $name $data2")`