getIntent返回null-Android

时间:2018-12-04 21:23:58

标签: java android

我有一个包含三个活动(MainActivity,PlayerActivity和ListActivity)的项目。我想将意图从MainActivity发送到PlayerActivity,并在PlayerActivity中选择一个名称,然后将其再次传递给MainActivity.

我写了另一种从ListActivityMainactivity发送数据的意图。

MainActivityListActivity的效果很好,也MainActivityPlayerActivity.都很完美,但是当PlayerActivity将Intent发送到MainActivity时,我得到了一个空意图

这是我的代码:

从ListActivity发送:

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();

            int buttonId = bundle.getInt("buttonID");
            String name = parent.getItemAtPosition(position).toString();

            Intent sendIntentToMainActivity = new Intent(PlayersActivity.this, MainActivity.class);
            Bundle bundle1 = new Bundle();

            bundle1.putString("name", name);
            bundle1.putInt("buttonId", buttonId);

            startActivity(sendIntentToMainActivity);

        }
    });

进入MainActivity:

@Override
protected void onNewIntent(Intent intent) {
    if (intent != null) {
        setIntent(intent);
        Log.d("xxx", "Intent is null");
    }
}

@Override
protected void onResume() {
    super.onResume();

    Intent intent = getIntent();
    Bundle bundle = new Bundle();

    int id = bundle.getInt("buttonID");
    String name = bundle.getString("name");

    if (id == mButton_first_group_frist_name.getId()) {
        mButton_first_group_frist_name.setText(name);
    } else if (id == mButton_first_group_second_name.getId()) {
        mButton_first_group_second_name.setText(name);
    } else if (id == mButton_second_group_frist_name.getId()) {
        mButton_second_group_frist_name.setText(name);
    } else if (id == mButton_second_group_second_name.getId()) {
        mButton_second_group_second_name.setText(name);
    }
}

请帮助并提供建议

1 个答案:

答案 0 :(得分:0)

您必须将捆绑软件添加到创建的意图中,当回到onResume时,从意图中获取捆绑软件。您可以这样操作:

Intent sendIntentToMainActivity = new Intent(PlayersActivity.this, MainActivity.class);
            Bundle bundle1 = new Bundle();

            bundle1.putString("name", name);
            bundle1.putInt("buttonId", buttonId);


            sendIntentToMainActivity.putExtra("bundle",bundle1);
            startActivity(sendIntentToMainActivity);

然后在onResume内:

Intent intent = getIntent();
    Bundle bundle = intent.getBundleExtra("bundle");