1

IDE: Android Studio

I want to write a program that when a user pressed down the KEYCODE_DPAD_UP button(like the up button on an Xbox One controller), the value of a member variable of a customized class will be increased. However, when I debug the program on my physical phone, if I pressed down the KEYCODE_DPAD_UP button, the program will shut down and an exception will be thrown:

java.lang.NullPointerException: Attempt to read from field 'int com.example.myClass.MainActivity$Demo.number' on a null object reference

Here is the code, it's a quite simple demo. I guess the myclass in function onKeyDown is not initialized, so myclass.number can't be solved. Thanks for anyone's help.

package com.example.Demo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;

public class MainActivity extends AppCompatActivity {
    myClass myclass;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final myClass myclass = new myClass();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_UP) { myclass.number++; }
        return true;
    }

    public class myClass{ public int number; }
}
TianaoLu
  • 11
  • 2
  • You never initialized `myclass` which is global you create a another local variable `myclass` change the line to `myclass = new myClass();` only . Please respect [java naming convention](https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html). – ADM Oct 27 '20 at 05:18
  • @ADM THANK YOU, THE PROBLEM IS SOVLED. I am such a noob. And thanks for reminding me of the naming convention. – TianaoLu Oct 27 '20 at 06:43

0 Answers0