How to pass parameters between two Activitis on Android

Tiempo de lectura: < 1 minuto

Reading Time: < 1 minute

In today’s article, I’m going to show you how to pass parameters between two Activities in Android using Java.

We can pass all types of variables from one Activity to another, including objects.

The first thing we need to do is create the intent to open a new Activity as follows:

Intent intent = new Intent(this, Activity2.class);
startActivity(intent);

With this intent, we can open the Activity2 screen.

If we want to send a variable using this intent, we need to add the following:

Intent intent = new Intent(this, Activity2.class);
intent.putExtra("variable", 1);
startActivity(intent);

In this case, we pass a variable which is an integer number 1.

To receive this variable in the Activity called Activity2, we need to add this code inside the onCreate method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
scss
Copy code
int numero = (int) getIntent().getSerializableExtra("variable");

...
}

With this code, we obtain the variable we passed and named “variable”, perform a cast to an integer (int), and can use it in the activity.

We can also pass an object using the previous code, but the object we pass must implement Serializable:

public class ExampleObject implements Serializable {
}

This way, we can pass it to another activity using an intent:

Intent intent = new Intent(this, Activity2.class);
ExampleObject obj = new ExampleObject();
intent.putExtra("object", obj );
startActivity(intent);

To receive it in the other activity, we need to put the following:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
scss
Copy code
ExampleObject obj = (ExampleObject) getIntent().getSerializableExtra("object");

...
}

And that concludes today’s article.

Leave a Comment