使用 getIntent().getExtras().getString 时出现空指针异常 [英] nullpointerexception when use getIntent().getExtras().getString

查看:34
本文介绍了使用 getIntent().getExtras().getString 时出现空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个活动中的值传递给另一个活动并使用此代码

I want to pass a value in a activity to another activity and use this code

            Intent i = new Intent(MainActivity.this,ListActivity.class);
            i.putExtra("position","ایران");
            startActivity(i);

在其他活动中返回变量使用此代码

and in other activity for return variable use this code

        value = getIntent().getExtras().getString("position");

现在,当我运行程序时,它给出了这个错误:

Now when I run the program it gives this error:

java.lang.nullpointerexception

请帮帮我.

推荐答案

这是检索额外字符串的正确方法:

This is the right way to retrieve string extra:

value = getIntent().getStringExtra("position");

说明

为什么 getExtras() 不起作用:getExtras() 返回先前使用 putExtras(bundle) 放入意图中的包.所以,代码看起来像:

Why getExtras() does not work: getExtras() returns a bundle which was previously put inside intent using putExtras(bundle). so, the code would look like:

    // Put position inside intent using extras:
    Intent intent = new Intent();
    Bundle extras = new Bundle();
    extras.putString("position",position);
    intent.putExtras(extras);

    // Retrieve position:
    getIntent().getExtras().getString("position");

但那是更多的代码,直接将额外的存储在意图中是更简洁的方式

But that's a lot more code, storing extra inside the intent directly is much more cleaner way

这篇关于使用 getIntent().getExtras().getString 时出现空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆