-1

As this answer, I need to pass a value from my main Activity to a custom View.After clicked a button, the createBall() will be called.And then pass the values to custom view.But after I click the button I get this error.

com.example.ball E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ball, PID: 12141
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.ball.customView.fresh(int, int, int)' on a null object reference

here is my MainActivity

public class MainActivity extends AppCompatActivity {

    private WindowManager wml;
    private customView myCus;
...
    private void createBall(int radius) {

        if (radius > 150) return;
        WindowManager wm1 = this.getWindowManager();
        int width = wm1.getDefaultDisplay().getWidth();
        int height = wm1.getDefaultDisplay().getHeight();
        myCus.fresh(width, height, radius);

    }
}

here is my custom view

...
public void fresh(int width, int height, int r) {
    radius = (int)r;
    x = (int)Math.random() * (width - radius * 2);
    y = (int)Math.random() * (height - radius * 2);
...
    invalidate();
}

Can you fix it for me, thx.

suedar
  • 130
  • 10
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – PPartisan Nov 21 '18 at 11:40
  • It says in the stacktrace that `customView` is `null` - where do you initialise it? – PPartisan Nov 21 '18 at 11:41
  • @suedar You have to initialize the customView class inside createBall method of MainActivity as follow: myCus = new customView(); – Muthuraja Nov 21 '18 at 11:47

1 Answers1

0

You must first create your view and then use its instance. your object of custom view is null

It's best to get an instance of the custom view from the Java code and add it to the root view of the layout using the addView() function. then call fresh on this object

Majid Ahmadi Jebeli
  • 517
  • 1
  • 6
  • 22
  • It seems that `fresh()` in the custom view is not called.So back to this question, how to call this function. – suedar Nov 21 '18 at 12:17