Janjan Janjan - 3 months ago 22
Android Question

Android studio Attempt to invoke virtual method on a null object reference

I am very new to android programming and this application I'm working on always throws a null object reference. I want to change the color of the circle if I press a colored button. My reset button also throws the same error and I don't know how to fix it. I tried everything I know and can't find any answer. Here is my code:

package com.example.myname.fingerpaintapplication;


import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;



public class MainActivity extends AppCompatActivity implements OnClickListener{

private DrawView drawView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

drawView = (DrawView) findViewById(R.id.draw_view);

Button myRedButton = (Button) findViewById(R.id.buttonRed);
myRedButton.setOnClickListener(this);

Button myBlueButton = (Button) findViewById(R.id.buttonBlue);
myBlueButton.setOnClickListener(this);

Button myGreenButton = (Button) findViewById(R.id.buttonGreen);
myGreenButton.setOnClickListener(this);

Button myBrownButton = (Button) findViewById(R.id.buttonBrown);
myBrownButton.setOnClickListener(this);

Button myVioletButton = (Button) findViewById(R.id.buttonViolet);
myVioletButton.setOnClickListener(this);

Button myYellowButton = (Button) findViewById(R.id.buttonYellow);
myYellowButton.setOnClickListener(this);

Button myExitButton = (Button) findViewById(R.id.buttonExit);
myExitButton.setOnClickListener(this);

Button myResetButton = (Button) findViewById(R.id.buttonReset);
myResetButton.setOnClickListener(this);

Button mySaveButton = (Button) findViewById(R.id.buttonSave);
mySaveButton.setOnClickListener(this);
}

@Override
public void onClick(View view) {
Button btnPressed = (Button)view;


if(btnPressed.getId() == R.id.buttonRed)
{
drawView.setColors(0xffff0000);
// use system log to indicate button1 pressed
Log.e("buttonRed","clicked");

// drawView.setColors(#ffff0000);

CharSequence text = "Red color selected";
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();
}

else if(btnPressed.getId() == R.id.buttonBlue)
{
// use system log to indicate button1 pressed
Log.e("buttonBlue","clicked");
drawView.setColors(Color.BLUE);
// pressedColor = Color.parseColor();
// create a Toast message
CharSequence text = "Blue color selected";
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();

}
else if(btnPressed.getId() == R.id.buttonGreen)
{
// use system log to indicate button1 pressed
Log.e("buttonGreen","clicked");
drawView.setColors(0x008000);
// pressedColor = Color.parseColor();
// create a Toast message
CharSequence text = "Green color selected";
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();

}
else if(btnPressed.getId() == R.id.buttonBrown)
{
// use system log to indicate button1 pressed
Log.e("buttonBrown","clicked");
drawView.setColors(0xa5682a);
// pressedColor = Color.parseColor();
// create a Toast message
CharSequence text = "Brown color selected";
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();

}
else if(btnPressed.getId() == R.id.buttonViolet)
{
// use system log to indicate button1 pressed
Log.e("buttonViolet","clicked");
drawView.setColors(0xFFC0CB);
// pressedColor = Color.parseColor();
// create a Toast message
CharSequence text = "Violet color selected";
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();

}
else if(btnPressed.getId() == R.id.buttonYellow)
{
// use system log to indicate button1 pressed
Log.e("buttonYellow","clicked");
drawView.setColors(0xffff00);
// pressedColor = Color.parseColor();
// create a Toast message
CharSequence text = "Yellow color selected";
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();

}

else if(btnPressed.getId() == R.id.buttonReset)
{

AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
newDialog.setTitle("Reset painting");
newDialog.setMessage("Start new painting? You will lose the current painting if you proceed");
newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
drawView.reset();
dialog.dismiss();
}
});
newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
newDialog.show();
}

else if (btnPressed.getId() == R.id.buttonExit)
{
AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
newDialog.setTitle("Exit application");
newDialog.setMessage("Exit the application?");
newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
finish();
dialog.dismiss();
}
});
newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
newDialog.show();
}


}

}


And this is my custom View:

package com.example.myname.fingerpaintapplication;

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


public class DrawView extends View{

public final static int CircleRadius = 50;
public final static int START_X = 0;
public final static int START_Y = 0;
private Paint paint, paintCanvas = new Paint();
private int paintCode = 0xffff0000;
private Bitmap customBitmap;
private Canvas customCanvas;


public DrawView(Context context) {
super(context);

}


public DrawView(Context context, AttributeSet attrs) {
this (context);
drawSomething();
//super(context, attrs);

}

private void drawSomething(){
paint = new Paint();
paint.setColor(Color.BLUE);
}

@Override
protected void onDraw(Canvas canvas) {
//canvas.drawColor(Color.WHITE);
canvas.drawBitmap( customBitmap, START_X, START_Y, paintCanvas);
super.onDraw(canvas);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
customBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
customCanvas = new Canvas(customBitmap);
customCanvas.drawColor(Color.WHITE);
super.onSizeChanged(w, h, oldw, oldh);
}



public void reset(){
invalidate();
customCanvas.drawColor(Color.WHITE);

}

public void setColors(int newColor){
//paintCode = Color.parseColor(newColor);
//paint = new Paint();
paintCode = newColor;
paint.setColor(paintCode);
invalidate();

// paintCode = Color.parseColor(newColor);
// paint.setColor(Integer.parseInt(newColor));

}

@Override
public boolean onTouchEvent(MotionEvent event)
{
super.onTouchEvent(event);

float x = event.getX();
float y = event.getY();
customCanvas.drawCircle(x, y, CircleRadius, paint);

invalidate();
return true;
}


}


and my activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="0dp"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
tools:context="com.example.myname.fingerpaintapplication.MainActivity"
android:background="#11b8dd">

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonRed"
android:background="#ff0000"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonYellow"
android:background="#ffff00"
android:layout_marginStart="10dp"
android:layout_alignTop="@+id/buttonViolet"
android:layout_toEndOf="@+id/buttonViolet" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonGreen"
android:background="#008000"
android:layout_below="@+id/buttonRed"
android:layout_toStartOf="@+id/buttonYellow"
android:layout_marginTop="15dp" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonBlue"
android:background="#0000ff"
android:layout_above="@+id/buttonGreen"
android:layout_alignStart="@+id/buttonYellow" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonViolet"
android:background="#FFC0CB"
android:layout_below="@+id/buttonGreen"
android:layout_alignParentStart="true"
android:layout_marginTop="15dp" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonBrown"
android:background="#a5682a"
android:layout_alignTop="@+id/buttonGreen"
android:layout_alignStart="@+id/buttonBlue" />

<com.example.myname.fingerpaintapplication.DrawView
android:id="@+id/draw_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toEndOf="@+id/buttonYellow"
android:layout_marginLeft="5dp"
android:layout_marginBottom="70dp" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="Exit"
android:id="@+id/buttonExit"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="15dp"
android:layout_marginRight="5dp" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="Reset"
android:id="@+id/buttonReset"
android:layout_alignTop="@+id/buttonExit"
android:layout_toEndOf="@+id/buttonSave" />

<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/buttonSave"
android:layout_alignTop="@+id/buttonReset"
android:layout_marginLeft="110dp" />

<ImageButton
android:layout_width="40dp"
android:layout_height="30dp"
android:id="@+id/imageButtonTriangle"
android:layout_marginTop="0dp"
android:src="@android:drawable/ic_media_play"
android:background="#11b8dd"
android:layout_marginLeft="30dp"
android:layout_alignParentStart="true"
android:layout_below="@+id/buttonYellow" />

<ImageButton
android:layout_width="35dp"
android:layout_height="35dp"
android:id="@+id/imageButton"
android:layout_below="@+id/imageButtonTriangle"
android:layout_alignStart="@+id/imageButtonTriangle"
android:paddingTop="7dp" />

<ImageButton
android:layout_width="40dp"
android:layout_height="30dp"
android:id="@+id/imageButton2"
android:src="@drawable/abc_switch_thumb_material"
android:background="#11b8dd"
android:layout_below="@+id/imageButton"
android:layout_alignStart="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton"
android:paddingTop="10dp" />

</RelativeLayout>


If I press the red button, it should change the color of the ball but instead it throws a null object reference. How do I fix this?

Thank you.

Here is the error:

09-01 13:49:28.240 19321-19321/com.example.francisjan.fingerpaintapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.francisjan.fingerpaintapplication, PID: 19321
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.francisjan.fingerpaintapplication.DrawView.setColors(int)' on a null object reference
at com.example.myname.fingerpaintapplication.MainActivity.onClick(MainActivity.java:65)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Answer

There is something wrong in your DrawView.java

about line 29,it should be

 public DrawView(Context context, AttributeSet attrs) {
    super(context, attrs);
    drawSomething();
}

You forget to invole the super method!!

Comments