368

Can someone please tell me how exactly to use getExtra() and putExtra() for intents? Actually I have a string variable, say str, which stores some string data. Now, I want to send this data from one activity to another activity.

  Intent i = new Intent(FirstScreen.this, SecondScreen.class);   
  String keyIdentifer  = null;
  i.putExtra(strName, keyIdentifer );

and then in the SecondScreen.java

 public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.table);
        TextView userName = (TextView)findViewById(R.id.userName);
        Bundle bundle = getIntent().getExtras();

        if(bundle.getString("strName")!= null)
        {
            //TODO here get the string stored in the string variable and do 
            // setText() on userName 
        }

    }

I know it is very basic question but unfortunately I am stuck here. Please help.

Thanks,

Edit: Here the string which I am trying to pass from one screen to the other is dynamic. That is I have an editText where I am getting string whatever user types. Then with the help of myEditText.getText().toString() . I am getting the entered value as a string then I have to pass this data.

1
  • i.putExtra(strName, keyIdentifer ); This statement has strName variable while bundle.getString("strName") has "strName" String. Its intent.putExtra(key, value) and intent.getExtras().getString(key); make sure you are using same key in put and get.
    – seema
    Commented Apr 29, 2015 at 12:30

18 Answers 18

459

Use this to "put" the file...

Intent i = new Intent(FirstScreen.this, SecondScreen.class);   
String strName = null;
i.putExtra("STRING_I_NEED", strName);

Then, to retrieve the value try something like:

String newString;
if (savedInstanceState == null) {
    Bundle extras = getIntent().getExtras();
    if(extras == null) {
        newString= null;
    } else {
        newString= extras.getString("STRING_I_NEED");
    }
} else {
    newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
3
  • 12
    is the "savedInstanceState..." and "...getSerialiable" code used to handle orientation changes? if no, what is that code used for?
    – AJW
    Commented Mar 19, 2017 at 20:14
  • 1
    I'm using android 3.0.1 and I had to use this.getActivity().getIntent().getExtras().
    – Tyler
    Commented Apr 6, 2018 at 12:44
  • If you use PendingIntents, you need to use the "PendingIntent.FLAG_UPDATE_CURRENT" flag: stackoverflow.com/a/29846408/2738240 Intent intent = new Intent(context, MainActivity.class); intent.putExtra("button_id", 1); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_test_widget); views.setOnClickPendingIntent(R.id.my_test_widget_button_1, pendingIntent); Commented May 10, 2020 at 21:15
80

first Screen.java

text=(TextView)findViewById(R.id.tv1);
edit=(EditText)findViewById(R.id.edit);
button=(Button)findViewById(R.id.bt1);

button.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
        String s=edit.getText().toString();

        Intent ii=new Intent(MainActivity.this, newclass.class);
        ii.putExtra("name", s);
        startActivity(ii);
    }
});

Second Screen.java

public class newclass extends Activity
{
    private TextView Textv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.intent);
        Textv = (TextView)findViewById(R.id.tv2);
        Intent iin= getIntent();
        Bundle b = iin.getExtras();

        if(b!=null)
        {
            String j =(String) b.get("name");
            Textv.setText(j);
        }
    }
}
56

Best Method...

SendingActivity

Intent intent = new Intent(SendingActivity.this, RecievingActivity.class);
intent.putExtra("keyName", value);  // pass your values and retrieve them in the other Activity using keyName
startActivity(intent);

RecievingActivity

 Bundle extras = intent.getExtras();
    if(extras != null)
    String data = extras.getString("keyName"); // retrieve the data using keyName 

/// shortest way to recieve data..

String data = getIntent().getExtras().getString("keyName","defaultKey");

//This requires api 12. //the second parameter is optional . If keyName is null then use the defaultkey as data.

0
25

This is what i have been using, hopfully it helps someone.. simple and affective.

send data

    intent = new Intent(getActivity(), CheckinActivity.class);
    intent.putExtra("mealID", meal.Meald);
    startActivity(intent);

get data

    int mealId;

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();

    if(bundle != null){
        mealId = bundle.getInt("mealID");
    }

cheers!

1
  • 1
    I still have to remind my self, now and then, how this was done properly.. lol! Commented Sep 15, 2015 at 22:30
11

It is very easy to implement intent in Android.. It takes you to move from one activity to another activity,we have to two method putExtra(); and getExtra();Now I am showing you the example..

    Intent intent = new Intent(activity_registration.this, activity_Login.class);
                intent.putExtra("AnyKeyName", Email.getText().toString());  // pass your values and retrieve them in the other Activity using AnyKeyName
                        startActivity(intent);

Now we have to get the value from AnyKeyName parameter,the below mentioned code will help in doing this

       String data = getIntent().getExtras().getString("AnyKeyName");
        textview.setText(data);

We can easily set the receiving value from Intent,wherever we required.

7

A small addendum: you do not have to create your own name for the key, android provides these, f.ex. Intent.EXTRA_TEXT. Modifying the accepted answer:

Intent i = new Intent(FirstScreen.this, SecondScreen.class);   
String strName = null;
i.putExtra(Intent.EXTRA_TEXT, strName);

Then, to retrieve the value try something like:

String newString;
Bundle extras = getIntent().getExtras();
if(extras == null) {
    newString= null;
} else {
    newString= extras.getString(Intent.EXTRA_TEXT);
}
6
Intent intent = new Intent(view.getContext(), ApplicationActivity.class);
                        intent.putExtra("int", intValue);
                        intent.putExtra("Serializable", object);
                        intent.putExtra("String", stringValue);
                        intent.putExtra("parcelable", parObject);
                        startActivity(intent);

ApplicationActivity

Intent intent = getIntent();
Bundle bundle = intent.getExtras();

if(bundle != null){
   int mealId = bundle.getInt("int");
   Object object = bundle.getSerializable("Serializable");
   String string = bundle.getString("String");
   T string = <T>bundle.getString("parcelable");
}
6

send

startActivity(new Intent(First.this, Secend.class).putExtra("key",edit.getText.tostring));

get

String myData = getIntent.getStringExtra("key");
5

Update in Intent class.

  • Use hasExtra() for checking if intent has data on key.
  • You can use now getStringExtra() directly.

Pass Data

intent.putExtra(PutExtraConstants.USER_NAME, "user");

Get Data

String userName;
if (getIntent().hasExtra(PutExtraConstants.USER_NAME)) {
    userName = getIntent().getStringExtra(PutExtraConstants.USER_NAME);
}

Always put keys in constants as best practice.

public interface PutExtraConstants {
    String USER_NAME = "USER_NAME";
}
2
  • Why is PutExtraConstants an interface?
    – Big_Chair
    Commented Apr 9, 2019 at 13:11
  • @Big_Chair Because PutExtraConstants class contains only constants (public, static, final). So it is better to use interface for Constants. Commented Apr 9, 2019 at 13:13
4

More simple

sender side

Intent i = new Intent(SourceActiviti.this,TargetActivity.class);
i.putExtra("id","string data");
startActivity(i)

receiver side

Intent i = new Intent(SourceActiviti.this,TargetActivity.class);
String strData = i.getStringExtra("id");
1
  • I will always vote for simplicity especially where code does same thing. Commented Jul 16, 2020 at 13:22
4

Put String in Intent Object

  Intent intent = new Intent(FirstActivity.this,NextAcitivity.class);
  intent.putExtra("key",your_String);
  StartActivity(intent);

NextAcitvity in onCreate method get String

String my_string=getIntent().getStringExtra("key");

that is easy and short method

2

At FirstScreen.java

Intent intent = new Intent(FirstScreen.this, SecondScreen.class);
String keyIdentifier = null;
intent.putExtra(strName, keyIdentifier);

At SecondScreen.java

String keyIdentifier;
if (savedInstanceState != null)
    keyIdentifier= (String) savedInstanceState.getSerializable(strName);
else
    keyIdentifier = getIntent().getExtras().getString(strName);
1
1

put function

etname=(EditText)findViewById(R.id.Name);
        tvname=(TextView)findViewById(R.id.tvName);

        b1= (ImageButton) findViewById(R.id.Submit);

        b1.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                String s=etname.getText().toString();

                Intent ii=new Intent(getApplicationContext(), MainActivity2.class);
                ii.putExtra("name", s);
                Toast.makeText(getApplicationContext(),"Page 222", Toast.LENGTH_LONG).show();
                startActivity(ii);
            }
        });



getfunction 

public class MainActivity2 extends Activity {
    TextView tvname;
    EditText etname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity2);
        tvname = (TextView)findViewById(R.id.tvName);
        etname=(EditText)findViewById(R.id.Name);
        Intent iin= getIntent();
        Bundle b = iin.getExtras();

        if(b!=null)
        {

          String j2 =(String) b.get("name");

etname.setText(j2);
            Toast.makeText(getApplicationContext(),"ok",Toast.LENGTH_LONG).show();
        }
    }
1

Push Data

import android.content.Intent;

    ...

    Intent intent = 
        new Intent( 
            this, 
            MyActivity.class );
    intent.putExtra( "paramName", "paramValue" );
    startActivity( intent );

The above code might be inside the main activity. "MyActivity.class" is the second Activity we want to launch; it must be explicitly included in your AndroidManifest.xml file.

<activity android:name=".MyActivity" />

Pull Data

import android.os.Bundle;

    ...

    Bundle extras = getIntent().getExtras();
    if (extras != null)
    {
        String myParam = extras.getString("paramName");
    }
    else
    {
        //..oops!
    }

In this example, the above code would be inside your MyActivity.java file.

Gotchas

This method can only pass strings. So let's say you need to pass an ArrayList to your ListActivity; a possible workaround is to pass a comma-separated-string and then split it on the other side.

Alternative Solutions

Use SharedPreferences

1
  • and what if I want to pass a string from string.xml?
    – HB.
    Commented Feb 2, 2017 at 5:30
1

Simple, In first Activity-

    EditText name= (EditText) findViewById(R.id.editTextName);
    Button button= (Button) findViewById(R.id.buttonGo);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this,Main2Activity.class);
            i.putExtra("name",name.getText().toString());
           startActivity(i);
          }
    });

In second Activity-

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    TextView t = (TextView) findViewById(R.id.textView);
    Bundle bundle=getIntent().getExtras();
    String s=bundle.getString("name");
    t.setText(s);
}

You can add if/else conditions if you want.

0

put string first

Intent secondIntent = new Intent(this, typeof(SecondActivity));
            secondIntent.PutExtra("message", "Greetings from MainActivity");

retrieve it after that

var message = this.Intent.GetStringExtra("message");

thats All ;)

0

A single inlined code would be enough for this task. This worked for me effortlessly. For #android devlopers out there. String strValue=Objects.requireNonNull(getIntent().getExtras()).getString("string_Key");

-2

You can Simply use static variable to store the string of your edittext and then use that variable in the other class. Hope this will solve your problem

1
  • 4
    You can but you shouldn't :-)
    – Blundell
    Commented Feb 13, 2020 at 15:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.