导致java.lang.NullPointerException异常的一种情况

来源:互联网 发布:win10更新windows.old 编辑:程序博客网 时间:2024/05/20 18:44

先来看错误提示:

模拟器上的错误提示


LogCat窗口提示:

通过查android开发者帮助文档(http://developer.android.com/reference/java/lang/NullPointerException.html)我们知道,“java.lang.NullPointerException”异常是在程序尝试访问一个对象的字段/方法或者一个数组(Array)的元素时找不到相应的字段/方法或者元素而产生的(当然还有其他少见的可能该异常的情形)。原文截取如下:

Thrown when a program tries to access a field or method of an object or an element of an array when there is no instance or array to use, that is if the object or array points tonull. It also occurs in some other, less obvious circumstances, like athrow e statement where the Throwable reference isnull.

既然如此,通过查看源程序答案一目了然:

主Activity的部分代码如下

通过按键启动的另一个Activity部分代码如下

通过对比不难发现,主Activity中

                //在bundle中添加爱好
                String tmp_hobby="爱好:";
                if(reading.isChecked())
                    tmp_hobby+="阅读";
                if(swimming.isChecked())
                    tmp_hobby+=",游泳";

之后少了一句:bundle.putString("hobby", tmp_hobby);添上之后运行即可通过。


原创粉丝点击