Reputation: 2545
I have a problem with following simple code. I create GraphicView class which extends SurfaceView. I run it on another thread which starts at the onCreate method:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
GraphicView v = new GraphicView( this );
Thread thread = new Thread( v );
thread.start();
setContentView( v );
}
I don't know why but when I close my application - I get an error. I don't use english UI on my tablet but I think on english it sound like this: "There was an error in the application". And nothing more! Maybe I need to stop thread? Is there errors in my code?
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 );
}
}
}
So the error is:
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)
Line 192 of GraphicView.java:
c.drawARGB( 255, 128, 255, 80 );
Upvotes: 0
Views: 619
Reputation: 48242
Try replacing while(true) with while(!yourActivity.isFinishing())
Perhaps even better you should break your loop in Activity's onPause and resume it in onResume()
Upvotes: 1