传感器上的android java.lang.NullPointerException
我在玩加速计传感器,看看它是如何工作的,为此我想在TextView上实时显示手机移动的力度。 但是每次我按下btnStart按钮时,它都会给出java.lang.NullPointerException错误。但是我真的看不到我的代码中的错误,我想它发生在我声明传感器时,但它没有任何意义,因为这是声明它的最佳方式。 代码: } 在xml中:传感器上的android java.lang.NullPointerException,android,nullpointerexception,sensors,Android,Nullpointerexception,Sensors,我在玩加速计传感器,看看它是如何工作的,为此我想在TextView上实时显示手机移动的力度。 但是每次我按下btnStart按钮时,它都会给出java.lang.NullPointerException错误。但是我真的看不到我的代码中的错误,我想它发生在我声明传感器时,但它没有任何意义,因为这是声明它的最佳方式。 代码: } 在xml中: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" x
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Start" />
<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnStart"
android:layout_below="@+id/btnStart"
android:layout_marginTop="37dp"
android:text="Stop" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/btnStart"
android:layout_centerHorizontal="true"
android:layout_marginBottom="89dp"
android:textAppearance="@android:style/TextAppearance.Medium"
android:text="TextView" />
您需要在onCreate方法中初始化sensorManager,否则当您按下按钮并使用以下命令时,它当然将为空:
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
将导致您遇到的NullPointerException
在onCreate中添加类似的内容:
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
您刚刚为
传感器管理器
声明了变量。你忘了初始化它。因此,在onCreate()
方法上初始化它。像
sensorManager = (SensorManager)this.getSystemService(SENSOR_SERVICE);
发布logcat错误跟踪,并为我们指出源代码的哪一行对应于空指针“起因”中的编号行。在这一行中,识别您试图使用字段或方法的对象,并思考是什么样的失败导致该对象仍然为空。
sensorManager = (SensorManager)this.getSystemService(SENSOR_SERVICE);