环境 :android studio
构造函数中,开始声明了一个TextView
public class MainActivity extends ActionBarActivity {
private TextView MyTextView = null;
onCreate方法中我写下了findViewById:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyTextView = (TextView)this.findViewById(R.id.mytextview_id );
MyTextView.setText(“第一个TextView”);
虽然能够正常运行,但是竟然出现了错误:
Process: com.zhangjw.buttonandtext, PID: 4428
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.zhangjw.buttonandtext/com.zhangjw.buttonandtext.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method “”android.view.View android.view.Window.findViewById(int)”” on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method “”android.view.View android.view.Window.findViewById(int)”” on a null object reference
at android.app.Activity.findViewById(Activity.java:2071)
at com.zhangjw.buttonandtext.MainActivity.<init>(MainActivity.java:12)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
????????????at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
????????????at android.app.ActivityThread.access$800(ActivityThread.java:144)
????????????at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
????????????at android.os.Handler.dispatchMessage(Handler.java:102)
????????????at android.os.Looper.loop(Looper.java:135)
????????????at android.app.ActivityThread.main(ActivityThread.java:5221)
????????????at java.lang.reflect.Method.invoke(Native Method)
????????????at java.lang.reflect.Method.invoke(Method.java:372)
????????????at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
????????????at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
希望各位大神能迅速为我答疑解惑. 为什么 出现空指针的问题?