To pass a string value between activities in Android, you can use an Intent
object and the putExtra
method to put the string value in the Intent
object as an extra.
Here is an example of how you can pass a string value between activities in Android:
re:ot reflautturi.comimport android.content.Intent; public class MainActivity extends AppCompatActivity { private String message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); message = "Hello, World!"; } public void openActivity(View view) { Intent intent = new Intent(this, SecondActivity.class); intent.putExtra("MESSAGE", message); startActivity(intent); } }
In this example, the MainActivity
activity has a string field called message
, and a method called openActivity
that is called when a button is clicked. The openActivity
method creates an Intent
object and puts the message
field in the Intent
object as an extra using the putExtra
method. The SecondActivity
class is specified as the target activity, and the Intent
object is used to start the SecondActivity
.
To get the string value from the Intent
object in the SecondActivity
class, you can use the getStringExtra
method of the Intent
class:
import android.content.Intent; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Intent intent = getIntent(); String message = intent.getStringExtra("MESSAGE"); // Do something with the message... } }
In this example, the SecondActivity
class gets the Intent
object in the onCreate
method using the getIntent
method and retrieves the string value from the Intent
object using the getStringExtra
method. The getStringExtra
method takes one argument: the name of the extra.
Keep in mind that this is just one way to pass a string value between activities in Android. You can use different methods and techniques to achieve the same result, such as using a Bundle
object to store the string value and pass it to the Intent
object, or using a global variable to store the string value and access it from any activity.