Pass a String from one Activity to another in Android

Reading Time: 1 minute

This article is about how to pass a string from one activity to another in Android studio. This action doesn’t require any changes in layout or manifest. Code in the button in activity that send string is as follows:

String s=”My Message”;

Prepare object of Bundle class.

Bundle basket= new Bundle();

We put string data into the variable, but use fixed string as an reference in bundle object.

basket.putString(“abc”, s);

Then use one Intent object for activating another activity.

Intent sendStuff = new Intent(this, MainActivity.class);
sendStuff.putExtras(basket);
startActivity(sendStuff);

If we want to close activity that is sending message we use:

//this.onBackPressed();
super.onBackPressed();

On the receiving activity, in onCreate method, we put just following code:

Intent intent = getIntent();
if (null != intent)
{

String stringData= intent.getStringExtra(“abc”);

Toast.makeText(this, stringData, Toast.LENGTH_LONG).show();

}

That’s it.

Tagged with:

Leave a Reply

Your email address will not be published. Required fields are marked *

*