How to pass values or some data to another activity using android studio with Kotlin or Java languages.? Sometimes it may require to pass some values from one activity to another to get the data there, so let’s see how to do it in android studio using both Kotlin and Java languages.
Pass value using Kotlin
Let’s simple pass values from one to another activity while navigating using intent in Kotlin as the example code below. Let’s add the value with intent just before starting the intent, then catch the same value on the second activity. If you don’t know how to navigate from one activity to another using Kotlin, read this.
val data = "This is a test"
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("data", "$data")
startActivity(intent)
Get the Data from second activity
var data: String =""
// initialize data as var above
val intent = intent
data = intent.getStringExtra("data").toString()
Pass Values using Java
As we did using Kotlin now let’s see how to do it Java language using Android Studio.
Intent intent = new Intent(MainActivity.this, PlayerActivity.class);
String data = "This is a test";
intent.putExtra("data", data);
startActivity(intent);
Get the value from Second activity
Intent intent = getIntent();
String data=intent.getStringExtra("data");
As mention above, passing data between activities is very easy with putExtra() and getExtra() function using Intent.