Reputation: 33
I want to pass the string from activity to other activities. For example, tell that I have 5 activities I get a text from the second to the third to the forth to the fifth but when I click a button to go to the third the text is not saved how can I save the string when I pass it?
i try to pass the text that i get from second activity to all the others with Intent:
//While on MainActivity
Intent Second = new Intent(MainActivity.this, SecondActivity.class);
startActivity(Second);
//While on SecondActivity
Intent Third = new Intent(SecondActivity.this, ThirdActivity.class);
Third.putExtra("Third", String);
startActivity(Third);
//While on ThirdActivity
TextView String;
String = findViewByID(R.id.TextView1);
String.setText(string);
String string = getIntent().getStringExtra("Third");
Intent Forth = new Intent(ThirdActivity.this, ForthActivity.class);
Forth.putExtra("Forth", string);
startActivity(Forth);
And i passing strings like that until Activity 5 that has a button that goes to the third and the textview text is not saved
I expected when I click the button from activity 5 that goes to the third activity the text view on third activity to be the text from the second activity that I pass it.
Upvotes: 1
Views: 432
Reputation: 4081
You can "forward" all extras using putExtras(intent):
Intent third = new Intent(this, ThirdActivity.class);
third.putExtras(getIntent());
third.putExtra("THIRD", myString);
This will maintain the same key at every step, so if you backtrack (Activity 5 => Activity 3) you can still extract the relevant values for that activity.
Since your extras might be read in multiple Activities, I would define constants in the final Activity in your flow (I assume a summary or confirmation activity):
public class LastActivity extends AppCompatActivity {
public static final String EXTRA_NAME = "EXTRA_NAME"
public static final String EXTRA_EMAIL = "EXTRA_EMAIL"
public static final String EXTRA_BOOKING_ID = "EXTRA_BOOKING_ID"
// rest of class
}
Then you don't risk typos when you putExtra
or getXxxExtra
:
String name = intent.getStringExtra(LastActivity.EXTRA_NAME);
Upvotes: 1