我遇到以下簡單代碼的問題。我創建了擴展SurfaceView的GraphicView類。我在這起始於onCreate方法的另一個線程中運行它:爲什麼我在退出應用程序時遇到應用程序崩潰?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GraphicView v = new GraphicView(this);
Thread thread = new Thread(v);
thread.start();
setContentView(v);
}
我不知道爲什麼,但是當我關閉我的應用程序 - 我得到一個錯誤。我在平板電腦上不使用英文界面,但我認爲使用英文聽起來像這樣:「應用程序出現錯誤」。沒有別的了!也許我需要停止線程?我的代碼中是否有錯誤?
public class GraphicView extends SurfaceView implements Runnable {
Activity activity;
SurfaceHolder holder;
Paint paint;
public GraphicView(Activity activity) {
super(activity);
this.activity = activity;
paint = new Paint();
paint.setColor(Color.YELLOW);
paint.setStyle(Style.FILL);
holder = getHolder();
}
@Override
public boolean onTouchEvent(MotionEvent me) {
return false;
}
public void run() {
while (true) {
if (!holder.getSurface().isValid()) {
continue;
}
Canvas c = holder.lockCanvas();
c.drawARGB(255, 128, 255, 80);
holder.unlockCanvasAndPost(c);
}
}
}
因此錯誤是:
10-31 00:02:20.124: W/KeyCharacterMap(278): No keyboard for id 0
10-31 00:02:20.124: W/KeyCharacterMap(278): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
10-31 00:02:21.104: W/dalvikvm(278): threadid=11: thread exiting with uncaught exception (group=0x4001d800)
10-31 00:02:21.124: E/AndroidRuntime(278): FATAL EXCEPTION: Thread-10
10-31 00:02:21.124: E/AndroidRuntime(278): java.lang.NullPointerException
10-31 00:02:21.124: E/AndroidRuntime(278): at com.example.GraphicView.run(GraphicView.java:192)
10-31 00:02:21.124: E/AndroidRuntime(278): at java.lang.Thread.run(Thread.java:1096)
線GraphicView.java 192:
c.drawARGB(255, 128, 255, 80);
您將需要發佈堆棧跟蹤/日誌貓,所以我們可以幫助 – Broak