Devin Tripp
Devin Tripp

Reputation: 147

creating a rectangle with words on it

so Im trying to draw a rectangle in my java project and for some reason im getting an error and the application shuts down. The error is 03-28 09:05:50.332: E/AndroidRuntime(4611): FATAL EXCEPTION: main 03-28 09:05:50.332: E/AndroidRuntime(4611): Process: com.Tripp.thebasics, PID: 4611 03-28 09:05:50.332: E/AndroidRuntime(4611): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Paint.setColor(int)' on a null object reference

package com.Tripp.thebasics;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class DrawingView extends View {
    Paint paint;

    public DrawingView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public DrawingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public DrawingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);

        Rect ourRect = new Rect();

        ourRect.set(0,0,canvas.getWidth(),canvas.getHeight()/2 );
        paint.setColor(Color.RED);

        canvas.drawRect(ourRect, paint);
    }

}

and here is the button that goes to that class below

public class JokeOfTheDay extends Activity {

    DrawingView v;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        v = new DrawingView(this);
        setContentView(v);  

    }



}

Upvotes: 0

Views: 147

Answers (2)

ejohansson
ejohansson

Reputation: 2882

Here are two good resources showing how to create custom views and painting.

Also take a look at this example showing how to create a PieChart view:

Upvotes: 0

Filipe Silva
Filipe Silva

Reputation: 220

Initialize the paint variable in your constructor before you try to use it. paint = new Paint();

Upvotes: 2

Related Questions