【问题标题】:intent.getStringExtra is always "null"intent.getStringExtra 始终为“null”
【发布时间】:2020-05-12 02:37:54
【问题描述】:

这是将字符串添加到 intent.putExtra 的方式:

    final ListView listView = findViewById(R.id.userListView);
    final ArrayList<String> usernames = new ArrayList<>();

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(getApplicationContext(), UserFeedActivity.class);
            String username = usernames.get(i);
            intent.putExtra("username", username.toString() );
            Log.i("test","username: "+username);
            startActivity(intent);

        }
    });

日志。我给了我:“... I/test: username: Chris2”,所以我认为额外添加的内容是正确的

但是,在 UserFeedActivity 类上,如果我尝试使用以下代码读取意图:

    Intent intent = new Intent();
    String username = intent.getStringExtra("username");
    Log.i("test2","username: "+username);

日志。我给了我:“... I/test2: username: null”

我也试过

    Bundle bundleEx = intent.getExtras();
    Log.i("trdt3","extras: "+bundleEx);

日志。我给了我:“... I/test3: extras: null”

是我做错了什么还是什么?

【问题讨论】:

    标签: android android-intent null android-intentservice extra


    【解决方案1】:

    您正在其他活动中创建一个全新的意图,因此它没有额外内容。在新活动中你需要调用getIntent(),像这样

    Intent intent = getIntent(); // don't use 'new Intent()' here
    String username = intent.getStringExtra("username");
    Log.i("test3","username: "+username);
    

    注意调用getStringExtra只是在内部调用getExtras(),然后是getString(...),所以和使用getIntent().getExtras().getString(...)是一样的

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      • 2022-01-20
      • 2016-01-14
      相关资源
      最近更新 更多