我有一个错误,我不明白是什么原因造成的。
这是生成错误的代码片段:
public class RssReader extends Activity {
private Button button1;
@Override
public void onCreate(Bundle savedInstanceState) {
button1 = (Button) findViewById(R.id.b1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("test");
}
});
super.onCreate(savedInstanceState);
setContentView(R.layout.rss_reader);
}
}
虽然这是我的rss_reader.xml
文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
</LinearLayout>
上面的代码导致 a NullPointerException
,但我无法理解我正在访问的空指针,因为我没有使用任何不安全的构造。完整的错误如下:
04-14 18:50:14.305: E/AndroidRuntime(443): FATAL EXCEPTION: main
04-14 18:50:14.305: E/AndroidRuntime(443): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cris96.rssreader/com.cris96.rssreader.RssReader}: java.lang.NullPointerException
04-14 18:50:14.305: E/AndroidRuntime(443): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
04-14 18:50:14.305: E/AndroidRuntime(443): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
04-14 18:50:14.305: E/AndroidRuntime(443): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-14 18:50:14.305: E/AndroidRuntime(443): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-14 18:50:14.305: E/AndroidRuntime(443): at android.os.Handler.dispatchMessage(Handler.java:99)
04-14 18:50:14.305: E/AndroidRuntime(443): at android.os.Looper.loop(Looper.java:123)
04-14 18:50:14.305: E/AndroidRuntime(443): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-14 18:50:14.305: E/AndroidRuntime(443): at java.lang.reflect.Method.invokeNative(Native Method)
04-14 18:50:14.305: E/AndroidRuntime(443): at java.lang.reflect.Method.invoke(Method.java:507)
04-14 18:50:14.305: E/AndroidRuntime(443): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-14 18:50:14.305: E/AndroidRuntime(443): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-14 18:50:14.305: E/AndroidRuntime(443): at dalvik.system.NativeStart.main(Native Method)
04-14 18:50:14.305: E/AndroidRuntime(443): Caused by: java.lang.NullPointerException
04-14 18:50:14.305: E/AndroidRuntime(443): at com.cris96.rssreader.RssReader.onCreate(RssReader.java:14)
04-14 18:50:14.305: E/AndroidRuntime(443): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-14 18:50:14.305: E/AndroidRuntime(443): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
04-14 18:50:14.305: E/AndroidRuntime(443): ... 11 more
我该如何解决?
谢谢