Question

How do I set a TextView's text to the input from the previous intent?

Answer and Explanation

To set a TextView's text to the input from the previous intent in Android, you'll need to follow these steps:

1. In the Activity that Sends the Intent:

- Put the data into the Intent as an extra before starting the new Activity.

- Use putExtra() method to add the data.

2. In the Activity that Receives the Intent:

- Get the Intent.

- Extract the data from the Intent using methods like getStringExtra(), getIntExtra(), etc., depending on the data type.

- Set the text of the TextView with the received data.

Here's an example:

Activity 1 (Sending Activity):

// In Activity 1
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("message", "Hello from Activity 1!"); // Put the data into the Intent
startActivity(intent);

Activity 2 (Receiving Activity):

// In Activity 2
TextView textView = findViewById(R.id.textView); // Get the TextView

Intent intent = getIntent(); // Get the Intent that started this Activity
String message = intent.getStringExtra("message"); // Extract the data

if (message != null) {
   textView.setText(message); // Set the TextView's text
} else {
   textView.setText("No message received");
}

Explanation:

- In Activity 1, an Intent is created to start Activity 2. The putExtra() method adds a string with the key "message" and value "Hello from Activity 1!".

- In Activity 2, the getIntent() method retrieves the Intent that started the activity. The getStringExtra("message") method extracts the string value associated with the key "message".

- The extracted string is then used to set the text of the TextView.

This is a simple way to pass data between activities in Android using Intents and TextView.

More questions