Pass Data from one activity to another

Steps

  • 1.Create a new android project with two activities ActivityA and ActivityB and corresponding xml layouts activity_a.xml and activity_b.xml
  • 2.Create an EditText in activity_a to take user input which will be passed to ActivityB
  • 3.On button click get the user input from the EditText and add it to the intent used for starting ActivityB
  • 4.In ActivityB retrieve and display the value passed from ActivityA

1.Create a new android project with two activities ActivityA and ActivityB and corresponding xml layouts activity_a.xml and activity_b.xml
In android studio go to File->New->New Project. Learn more

2.Create an EditText in activity_a to take user input which will be passed to ActivityB

Now the activity_a.xml looks like below:

And here is the activity_b.xml:

 

 

 

 

 

 

3. On button click get the user input from the EditText and add it to the intent used for starting ActivityB
To pass a value to the ActivityB we have to add it to the intent that will be used to start ActivityB as shown below:

Here intent.putExtra(“name”,name) has been supplied to parameters; first one is the name of the value to be passed (this will be used by the recieving activity to extract the value) and the value itself . The complete code for ActivityA is shown below:
4.In ActivityB retrieve and display the value passed from ActivityA
We have to access the intent that started this activity using getIntent() method of the Activity class.
And form this Intent object we shall retrieve the string sent by ActivityA using getStringExtra(String name) method of the Intent class.

Intent intent=getIntent();
String name=intent.getStringExtra(“name”);

Leave a Reply

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