0

I am beginner in Android Studio and recently my lecture gave me a lab assignment to create a simple game. This is the output.

enter image description here

And this is my output. My app crash when the ball hits the ground

enter image description here

This is the error i get

E/SensorManager: Exception dispatching input event. D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.myapplication, PID: 31130 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.example.myapplication.Game.onSensorChanged(Game.java:127) at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:837) at android.os.MessageQueue.nativePollOnce(Native Method) at android.os.MessageQueue.next(MessageQueue.java:335) at android.os.Looper.loop(Looper.java:183) at android.app.ActivityThread.main(ActivityThread.java:7656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

This is my Source Code for the java file

public class Game extends Activity implements SensorEventListener {

ImageView im;
ImageView im2;
int i = 0, j = 0;
SensorManager mSensorManager;
Sensor mSensor;
float m, n, b, v;
int vel = 10, vel2 = 10, z = 8, c = 8, f = 0, g = 0;
float k = 0;
boolean data = true, data2 = true;
MediaPlayer mp, mp2;
TextView tv, tv2;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
Context context = this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);
    sharedPref = Game.this.getSharedPreferences("xyz", Context.MODE_PRIVATE);
    editor = sharedPref.edit();
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    im = (ImageView) findViewById(R.id.imageView9);
    im2 = (ImageView) findViewById(R.id.imageView8);
    mp = MediaPlayer.create(this, R.raw.collision);
    mp2 = MediaPlayer.create(this, R.raw.toing);
    tv = (TextView) findViewById(R.id.tv1);
    tv2 = (TextView) findViewById(R.id.tv2);
    m = im2.getX();
    n = im2.getY();
}

@Override
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    float axisX = event.values[0];
    float axisY = event.values[1];
    float axisZ = event.values[2];

    b = im.getX();
    v = im.getY();

    if (axisX > 0 && m > 30) {
        if (data) {
            im2.setRotation(-10);
            data2 = true;
            data = false;
        }
        m = m - 20;
        im2.setX(m);
        z--;
        if (z == 0) {
            im2.setRotation(0);
            z = 8;
        }
    }
    if (axisX < 0 && m < 560) {
        if (data2) {
            im2.setRotation(10);
            data = true;
            data2 = false;
        }
        m = m + 20;
        im2.setX(m);
        c--;
        if (c == 0) {
            im2.setRotation(0);
            c = 8;
        }
    }
    if (b >= m - 60 && b <= m + 100 && v >= 870 && v <= 880) {
        vel2 = -vel2;
        if (sharedPref.getInt("y", 0) == 1) {
            mp.start();
        }
        f++;
        tv.setText(MessageFormat.format("Score:{0}", f));
    }
    if (b <= 42) {
        vel = 10;
    }
    if (v <= 52) {
        vel2 = 10;
    }
    if (b >= 592) {
        vel = -vel;
    }
    if (v >= 1002) {
        b = 592 / 2;
        v = 1002 / 2;

        if (sharedPref.getInt("x", 0) == 1) {
            mp2.start();
        }
        if (f >= sharedPref.getInt("HiScore", 0)) {
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.highscore2);
            dialog.setTitle("Yeah High Score");
            final EditText et = (EditText) dialog.findViewById(R.id.editText1);
            Button bt = (Button) dialog.findViewById(R.id.button1);
            dialog.show();

            bt.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    editor.putString("Name", String.valueOf(et.getText()));
                    editor.commit();
                    dialog.dismiss();
                }
            });

            editor.putInt("HiScore", f);
            editor.commit();
        }

        f = 0;
        tv.setText(MessageFormat.format("Score:{0}", String.valueOf(f)));
        tv2.setText(MessageFormat.format("Foul:{0}", String.valueOf(g)));
    }
    b = b + vel;
    v = v + vel2;
    im.setX(b);
    im.setY(v);
    im.setRotation(k);
    k += 1;
}

@Override
// TODO Auto-generated method stub
public void onAccuracyChanged(Sensor sensor, int accuracy) {}

protected void onResume()
    { // Register a listener for the sensor.
        super.onResume();
        mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }
    protected void onPause()
    {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }
}
Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
  • 1
    Does this answer your question? [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) – a_local_nobody Jul 06 '21 at 07:30
  • 1
    `Button bt` is `null`, is it placed inside `R.layout.highscore2`? – snachmsm Jul 06 '21 at 07:35
  • Thank you for responding to my question. I have tried you guys solution, i was to careless on the button linking part on my xml file. My program runs better now without errors. – Manimaran Mahesan Jul 06 '21 at 17:49

1 Answers1

0

Check the reference of your button in xml and used the correct with exact id and also checked if you have bind the same in you activity for the button. It's not finding the button id reference as it's not bind correctly.

  • Thank you for your help, this solution actually worked. I made a mistake on the xml file part which didn't include the correct button id. – Manimaran Mahesan Jul 06 '21 at 17:46