代碼如下:package com.example.android_4_1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyView myView = new MyView(this);
this.setContentView(myView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
感覺代碼沒什麼錯,但是在模擬機上打開就 The application....has stopped unexpectedly!調試的時候會彈出找不到源。不知道是不是我環境沒有搭建好。求幫忙~
08-12 14:39:12.440: D/AndroidRuntime(522): Shutting down VM
08-12 14:39:12.440: W/dalvikvm(522): threadid=1: thread exiting with uncaught exception (group=0x40015560)
08-12 14:39:12.490: E/AndroidRuntime(522): FATAL EXCEPTION: main
08-12 14:39:12.490: E/AndroidRuntime(522): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android_4_1/com.example.android_4_1.MainActivity}: java.lang.NullPointerException
08-12 14:39:12.490: E/AndroidRuntime(522): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-12 14:39:12.490: E/AndroidRuntime(522): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-12 14:39:12.490: E/AndroidRuntime(522): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-12 14:39:12.490: E/AndroidRuntime(522): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-12 14:39:12.490: E/AndroidRuntime(522): at android.os.Handler.dispatchMessage(Handler.java:99)
08-12 14:39:12.490: E/AndroidRuntime(522): at android.os.Looper.loop(Looper.java:123)
08-12 14:39:12.490: E/AndroidRuntime(522): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-12 14:39:12.490: E/AndroidRuntime(522): at java.lang.reflect.Method.invokeNative(Native Method)
08-12 14:39:12.490: E/AndroidRuntime(522): at java.lang.reflect.Method.invoke(Method.java:507)
08-12 14:39:12.490: E/AndroidRuntime(522): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-12 14:39:12.490: E/AndroidRuntime(522): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-12 14:39:12.490: E/AndroidRuntime(522): at dalvik.system.NativeStart.main(Native Method)
08-12 14:39:12.490: E/AndroidRuntime(522): Caused by: java.lang.NullPointerException
08-12 14:39:12.490: E/AndroidRuntime(522): at com.example.android_4_1.MyView.(MyView.java:14)
08-12 14:39:12.490: E/AndroidRuntime(522): at com.example.android_4_1.MainActivity.onCreate(MainActivity.java:13)
08-12 14:39:12.490: E/AndroidRuntime(522): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-12 14:39:12.490: E/AndroidRuntime(522): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-12 14:39:12.490: E/AndroidRuntime(522): ... 11 more
setContentView()調用2次了,把默認那個注釋掉在試試