识别NullPointerException原因

时间:2013-08-14 15:31:46

标签: android nullpointerexception

如何确定导致NullPointerException的确切原因?

08-14 20:25:56.703: E/AndroidRuntime(32491): FATAL EXCEPTION: main
08-14 20:25:56.703: E/AndroidRuntime(32491): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.joericharduz.akita/com.joericharduz.akita.MainActivity}: java.lang.NullPointerException
08-14 20:25:56.703: E/AndroidRuntime(32491):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at android.os.Looper.loop(Looper.java:130)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at android.app.ActivityThread.main(ActivityThread.java:3687)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at java.lang.reflect.Method.invokeNative(Native Method)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at java.lang.reflect.Method.invoke(Method.java:507)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at dalvik.system.NativeStart.main(Native Method)
08-14 20:25:56.703: E/AndroidRuntime(32491): Caused by: java.lang.NullPointerException
08-14 20:25:56.703: E/AndroidRuntime(32491):    at com.joericharduz.akita.MainActivity.onCreate(MainActivity.java:56)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-14 20:25:56.703: E/AndroidRuntime(32491):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
08-14 20:25:56.703: E/AndroidRuntime(32491):    ... 11 more

请提供建议如何找到NullPointerException。

第56行代码:

etSearch.findViewById(R.id.etSearch);

2 个答案:

答案 0 :(得分:3)

您尚未初始化etSearch。正确的方法就是这样:

etSearch = (EditText) findViewById(R.id.etSearch);

不是这个:etSearch.findViewById(R.id.etSearch);

确保首先调用了setContentView(...)。

答案 1 :(得分:0)

Public class MyActivity extends Activity{

EditText et;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et = (EditText)findViewById(R.id.yourId);
}
}

这是实例化activity元素的正确方法。你没有对EditText元素进行类型转换。