Passing Data Between Activities in Android

In Android development, it’s common to need to pass data from one activity to another. This can be achieved using Intents, which are a way to communicate between different components of an app. In this tutorial, we’ll explore how to send and receive data between activities using Intents.

Sending Data

To send data from one activity to another, you need to create an Intent object and use the putExtra() method to add the data you want to pass. The putExtra() method takes two parameters: a key (a string that identifies the data) and the value of the data.

Here’s an example:

String userName = "John Doe";
int userId = 123;

Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("user_name", userName);
intent.putExtra("user_id", userId);
startActivity(intent);

In this example, we’re sending two pieces of data: userName and userId. We’re using the keys "user_name" and "user_id" to identify these values.

Receiving Data

To receive data in another activity, you need to use the getIntent() method to get the Intent object that started the activity. Then, you can use the getStringExtra() or getIntExtra() methods to retrieve the data.

Here’s an example:

Intent intent = getIntent();
String userName = intent.getStringExtra("user_name");
int userId = intent.getIntExtra("user_id", 0); // default value is 0

// Use the received data as needed

Note that if the key is not found, getStringExtra() will return null and getIntExtra() will return the default value.

Alternatively, you can use the getExtras() method to retrieve a Bundle object that contains all the extra data. Then, you can use the getString() or getInt() methods to retrieve the data.

Bundle extras = getIntent().getExtras();
if (extras != null) {
    String userName = extras.getString("user_name");
    int userId = extras.getInt("user_id", 0); // default value is 0
}

Tips and Best Practices

  • Always check if the Intent has extra data before trying to retrieve it.
  • Use meaningful keys to identify your data, so that you can easily retrieve it in the receiving activity.
  • Be careful when passing sensitive data between activities, as Intents can be intercepted by other apps.

By following these steps and tips, you can effectively pass data between activities in Android using Intents.

Leave a Reply

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