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; }
}