Recipe 1.2 Passing Data Between Activities
The preceding recipe demonstrated how to launch another activity using the startActivity() method. One common task you need to perform when launching another activity is passing some data to it. For example, you might want to launch another activity to collect some user-related data, so you pass the name of the user to another activity. When the user has finished collecting all the data, the data also needs to be passed back to the calling activity. Hence, you need to be able to pass data back and forth between activities. This recipe shows you how.
Solution
You can make use of the Intent class to pass data to another activity. To pass primitive data types to another activity, you can use the putExtra() method, as the following code snippet shows:
package net.learn2develop.passingdata;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
Intent i = new
Intent("net.learn2develop.SecondActivity");
//---use putExtra() to add new key/value pairs---
i.putExtra("str1", "This is a string");
i.putExtra("age1", 25);
}
}
The preceding statements ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access