代码为什么由于加速度计而不断崩溃?

时间:2018-07-19 08:41:12

标签: java android

我正在制作一个程序,在摇动手机或按下按钮时会显示随机文本。我是新手,所以我导入了很多代码并尝试理解然后进行修改。

我可以肯定它是if (speed > SHAKE_THRESHOLD)中的正文,因为当它为空时它可以工作,但不会更改文本视图。

我的日志猫:

07-19 14:10:24.131 5671-5708/com.example.user.something E/Surface: getSlotFromBufferLocked: unknown buffer: 0xae64c640
07-19 14:10:33.019 5671-5671/com.example.user.something E/SensorManager: Exception dispatching input event.
07-19 14:10:33.019 5671-5671/com.example.user.something E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.user.something, PID: 5671
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.user.something.Main2Activity.onSensorChanged(Main2Activity.java:103)
        at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:481)
        at android.os.MessageQueue.nativePollOnce(Native Method)
        at android.os.MessageQueue.next(MessageQueue.java:323)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

我的代码是:

package com.example.user.something;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;

public class Main2Activity extends AppCompatActivity implements SensorEventListener {
    public SensorManager senSensorManager;
    public Sensor senAccelerometer;
    private long lastUpdate = 0;
    public float last_x, last_y, last_z;
    private static final int SHAKE_THRESHOLD = 600;
    public Button b2;
    public String[] songs, links;
    public Button b3;
    public String q;
    public String q1;
    public TextView tv;
    public static final Random rgenerator = new Random();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);

        b2 = (Button) findViewById(R.id.button2);
        b3 = (Button) findViewById(R.id.button3);
        final TextView tv = (TextView) findViewById(R.id.text1);
        final Resources res = getResources();
        links = res.getStringArray(R.array.links);
        songs = res.getStringArray(R.array.songs);

        tv.setText("My Awesome Text");

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String q = songs[rgenerator.nextInt(songs.length)];
                String q1 = links[rgenerator.nextInt(songs.length)];

                tv.setText(q);
            }
        });

        b3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent browserIntent = new Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse(q));
                startActivity(browserIntent);
            }
        });
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        Sensor mySensor = sensorEvent.sensor;

        if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float x = sensorEvent.values[0];
            float y = sensorEvent.values[1];
            float z = sensorEvent.values[2];

            long curTime = System.currentTimeMillis();

            if ((curTime - lastUpdate) > 100) {
                long diffTime = (curTime - lastUpdate);
                lastUpdate = curTime;

                float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

                if (speed > SHAKE_THRESHOLD) {
                    String q = songs[rgenerator.nextInt(songs.length)];
                    String q1 = links[rgenerator.nextInt(songs.length)];

                    tv.setText(q);
                }

                last_x = x;
                last_y = y;
                last_z = z;
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {}

    protected void onPause() {
        super.onPause();
        senSensorManager.unregisterListener(this);
    }

    protected void onResume() {
        super.onResume();
        senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }
}

1 个答案:

答案 0 :(得分:1)

您有2个名为tv的变量:一个从未初始化的实例变量和onCreate中已初始化的局部变量。不幸的是,在onSensorChanged中,您使用了从未初始化过的那个,因此使用了NullPointerException。