简体   繁体   English

如何在活动之间同步数据?

[英]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. 我在第一个活动中有TextView1,在第二个活动中有TextView2。 The 2nd Activity is started form the 1st. 从第一个活动开始第二个活动。 After that the data in TextView2 is changed. 之后,更改TextView2中的数据。 When I'll be back to the 1st Activity, the data in TextView1 has to be the same with TextView2's data. 当我回到第一个活动时,TextView1中的数据必须与TextView2的数据相同。 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. 我试图使用意图,但是不可能,因为第一个Activity崩溃了,因为我想它正在等待数据。

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: 您可以使用startActivityForResults打开第二个活动,当第二个活动应该关闭时,您可以调用:

 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: 在活动1中,您将在onActivityResult收到结果,并在活动1中使用Intent data更新textview,示例代码来自:

How to manage `startActivityForResult` on Android? 如何在Android上管理`startActivityForResult`?

You have to check that the call to getIntent() does not return null, as is the case when you first launch 1st Activity 您必须检查对getIntent()的调用是否不返回null,就像第一次启动1st Activity一样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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