两种方式之间的数据绑定活动

时间:2017-02-25 14:14:46

标签: java android

我有2项活动,需要main Activitysecond Activity发送一些数据,然后第二项活动会分析这些数据并发回回复,所以我在下面2个代码:

Main Activity

    import static tk.zillion.mobile.SecondActivity.EXTRA_STUFF;

  public class MainActivity extends Activity {
    private static int PICK_CONTACT_REQUEST = 0;
   private static final int SECOND_ACTIVITY_RESULT_CODE = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

   // Start the SecondActivity
    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
    intent.putExtra(Intent.EXTRA_TEXT, "my text");
    startActivityForResult(intent, SECOND_ACTIVITY_RESULT_CODE);

    finish();
  }

// This method is called when the second activity finishes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Toast.makeText(this, "I'm the Main activity", Toast.LENGTH_SHORT).show();
    // check that it is the SecondActivity with an OK result
    if (requestCode == SECOND_ACTIVITY_RESULT_CODE) {
        if (resultCode == RESULT_OK) {

            // get String data from Intent
            String returnString = data.getStringExtra(EXTRA_STUFF);

            // set text view with string
            Toast.makeText(this, "I'm the Main activity", Toast.LENGTH_SHORT).show();
        }
    }
}

Second Activity如下:

public class SecondActivity extends Activity {

static final String EXTRA_STUFF = "tk.zillion.mobile.EXTRA_STUFF";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = new Intent();
    String s = getIntent().getStringExtra(Intent.EXTRA_TEXT);
    Toast.makeText(this, "I'm the second activity " + s , Toast.LENGTH_SHORT).show();

    Bundle basket =new Bundle();
    basket.putString(EXTRA_STUFF, s);
    intent.putExtras(basket);
    setResult(RESULT_OK, intent);
    finish();
  }
}

第二个活动被正确触发,并从主要活动中接收数据,但一旦发回数据,onActivityResult就不会被触发!!

我该如何解决?感谢

2 个答案:

答案 0 :(得分:2)

不要在startActivityForResult之后调用finish(),否则将破坏启动第二个的MainActivity实例

答案 1 :(得分:2)

删除startActivityForResult()之后的finish()调用。您可以阻止后续活动返回结果,因为您从后面的任务中删除了带有finish()的MainActivity。