简体   繁体   中英

How to synchronize data between Activities?

I want data to be synchronized between two Activities. I have TextView1 inside 1st Activity and TextView2 inside 2nd Activity. The 2nd Activity is started form the 1st. After that the data in TextView2 is changed. When I'll be back to the 1st Activity, the data in TextView1 has to be the same with TextView2's data. I've tried to use intents, but it's not possible to be as the 1st Activity is crashed because it's waiting for the data, I suppose.

The 1st Activity:

.....

level = getIntent().getExtras().getString("level");
score = getIntent().getExtras().getString("score");

.....

The 2nd Activity:

.....

Intent intent = new Intent(2nd_activity.this, 1st_activity.class);
intent.putExtra("level", Integer.toString(level));
intent.putExtra("score", Integer.toString(score));

.....

I guess you have figured it out why it doesn't work. What do I need to do to solve this problem?

You can use startActivityForResults to open 2nd Activity, when 2nd activity is supposed to be closed then you call:

 Intent returnIntent = new Intent();
 returnIntent.putExtra("tv_text",tv.getText());
 setResult(RESULT_OK,returnIntent);     

and in activity 1, you will receive results in onActivityResult and update textview in activity 1 with Intent data , sample code is from:

How to manage `startActivityForResult` on Android?

You have to check that the call to getIntent() does not return null, as is the case when you first launch 1st Activity

Intent rcvdIntent = getIntent();
if (rcvdIntent != null) {
   level = rcvdIntent.getExtras().getString("level");
   score = rcvdIntent.getExtras().getString("score");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM