[android] How to use putExtra() and getExtra() for string data

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.

This question is related to android android-intent

The answer is


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.


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");

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");
}

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);
}

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!


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();
        }
    }

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);

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 ;)


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";
}

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");


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


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.


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.


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


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);
        }
    }
}

send

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

get

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

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