Abhinav Raja
Abhinav Raja

Reputation: 351

Android activity for canvas keeps crashing

As soon as I start the activity, the phone hangs and then crashes. Logcat does not show why it crashes.

I have a canvas where circles keep appearing from top of the screen one after another and move down in a line at a constant rate . Here is my code for onDraw:

 protected void onDraw(Canvas canvas)
{
     int dy = 1;
    paint.setColor(Color.WHITE);
    paint.setStyle(Paint.Style.STROKE);

    for (int i=0, j=0; i<= dy/55; i=i++, j=j+55){
        canvas.drawCircle(canvas.getWidth()/2, dy+j, 25, paint); // there is a horizontal distance of 5 between 2 circles
    }
        dy +=2;

    invalidate();       
}

I think it is too much to process. Do i need to do it in a different thread.

Upvotes: 0

Views: 187

Answers (1)

Henry
Henry

Reputation: 17841

The obvious problem why it's crashing:
You are calling invalidate() within onDraw() method. When you call invalidate(), it will call onDraw() method. So when you call invalidate() within onDraw() method, you have ended up creating an INFINITE loop that never ends.

So how to accomplish what you are trying to do? Yes you need to run this in a separate thread. Use Handlers and within that increment your dy value and then call invalidate() there. Something like this: https://stackoverflow.com/a/7787796/4747587

Upvotes: 1

Related Questions