sumowrestler sumowrestler - 2 months ago 12
Java Question

Having trouble drawing circle to screen

I am new to android programming and am trying to draw a circle on the screen. Eventually I'd like to have the circle move around. But for now I have been having trouble getting the circle to draw. When I run the code, it gives me an error:


"Attempt to invoke virtual method 'long
android.graphics.Paint.getNativeInstance()' on a null"


My Code:


package com...

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}

class MyView extends View {



private Bitmap b;
public Paint p;

public MyView(Context context) {
super(context);
Paint p = new Paint();
p.setColor(Color.GREEN);
b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawCircle(50, 50, 10, p);
}
}
}

N J N J
Answer

Problem with your code is

 public MyView(Context context) {
            super(context);
            Paint p = new Paint();// Problem is here this is local declaration
            p = new Paint() // do like this and remove above line
            p.setColor(Color.GREEN);
            b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
        }