Android getIntent().getExtras() 返回 null

2022-09-01 03:20:28

我正在尝试在两个活动之间传递字符串。我已经在其他项目中使用相同的方法完成了此操作,但是由于某种原因,当我调用 intent.getStringExtra(String) 时,我得到了一个 NullPointerException。我还尝试通过以下方式为附加内容创建捆绑包

Bundle b = getIntent().getExtras();

但这也返回了空值。以下是我当前尝试使用的代码。

活动 A:

Intent myIntent = null; 
    String select = "";
            if (selection.equals("Chandelle")) {
                myIntent = new Intent(Commercial.this, Chandelle.class);
                select = "Chandelle";
            } else if (selection.equals("Eights on Pylons")) {
                myIntent = new Intent(Commercial.this, EightsOnPylons.class);
                select = "Eights on Pylons";
            }
 // Start the activity
    if (myIntent != null) {
        myIntent.putExtra("selection", select);
        Log.d("*** OUTBOUND INTENT: ", "" + myIntent.getExtras().get("selection"));
        startActivity(myIntent);
    }

下面是活动 B 中尝试提取额外内容的代码:

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 

    Intent i = getIntent();

    if (i == null) 
        Log.d("***DEBUG****", "Intent was null");
    else
        Log.d("**** DEBUG ***", "Intent OK");

    String MANEUVER_ID  = i.getStringExtra("selection"); //Exception points to this line
    Log.d("*** DEBUG", rec + " " + MANEUVER_ID);

我几乎尝试了所有传递额外内容的替代方法,但它们似乎都以这种方式运行。我错过了什么?


答案 1

添加到,以便它是.ToString()myIntent.putExtra("selection", select);myIntent.putExtra("selection", select.ToString());


答案 2

幸运的是,我找到了这篇文章。我已经为此挣扎了几个小时,最后我意识到我也在向tabHost发送我的意图。;-)对于那些仍然遇到问题的人来说,只需从tabHost活动本身获取附加功能并将其传递到子选项卡即可。

String userID;

..

 Bundle getuserID = getIntent().getExtras();
    if (getuserID != null) {
        userID = getuserID.getString("userID");
    }

...

 intent = new Intent().setClass(this, Games.class);
    intent.putExtra("userID", userID);
    spec = tabHost.newTabSpec("games").setIndicator("Games",
                      res.getDrawable(R.drawable.tab_games))
                  .setContent(intent);
    tabHost.addTab(spec);

推荐