[英]How to resolve Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
I am getting this error while running my app. 运行我的应用程序时出现此错误。 I can't figure out what to do.
我不知道该怎么办。
Here's my MainActivity.java 这是我的MainActivity.java
package com.example.user.sensor;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private float lastX = 0, lastY = 0, lastZ = 0;
private SensorManager sensorManager;
private Sensor accelerometer;
private float deltaXMax = 0;
private float deltaYMax = 0;
private float deltaZMax = 0;
private float deltaX = 0;
private float deltaY = 0;
private float deltaZ = 0;
private float vibrateThreshold = 0;
TextView currentX, currentY, currentZ;
public Vibrator v;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().getThemedContext();
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(getSupportActionBar().getThemedContext(), android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(getSupportActionBar().getThemedContext());
}
builder.setTitle("Alert Dialog")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
// success! we have an accelerometer
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
vibrateThreshold = accelerometer.getMaximumRange() / 2;
} else {
// fai! we dont have an accelerometer!
}
//initialize vibration
v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
}
//onResume() register the accelerometer for listening the events
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
//onPause() unregister the accelerometer for stop listening the events
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
// clean current values
displayCleanValues();
// display the current x,y,z accelerometer values
displayCurrentValues();
// display the max x,y,z accelerometer values
// get the change of the x,y,z values of the accelerometer
deltaX = Math.abs(lastX - event.values[0]);
deltaY = Math.abs(lastY - event.values[1]);
deltaZ = Math.abs(lastZ - event.values[2]);
// if the change is below 2, it is just plain noise
if (deltaX < 2)
deltaX = 0;
if (deltaY < 2)
deltaY = 0;
if (deltaZ > (vibrateThreshold) || (deltaY > vibrateThreshold) || (deltaZ > vibrateThreshold)) {
v.vibrate(50);
}
}
public void displayCleanValues() {
currentX.setText("0.0");
currentY.setText("0.0");
currentZ.setText("0.0");
}
// display the current x,y,z accelerometer values
public void displayCurrentValues() {
currentX.setText(Float.toString(deltaX));
currentY.setText(Float.toString(deltaY));
currentZ.setText(Float.toString(deltaZ));
}
}
// display the max x,y,z accelerometer values
activity_main.xml activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:layout_marginLeft="15dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GYROSCOPE"
android:textColor="@android:color/black"
android:layout_marginTop="30dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="8dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X :"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Y :"
android:layout_marginTop="4dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Z :"
android:layout_marginTop="4dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ACCELEROMETER"
android:textColor="@android:color/black"
android:layout_marginTop="30dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="8dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X :"
/>
<TextView
android:id="@+id/currentX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Y :"
android:layout_marginTop="4dp"
/>
<TextView
android:id="@+id/currentY"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Z :"
android:layout_marginTop="4dp"
/>
<TextView
android:id="@+id/currentZ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
and here is the log file: 这是日志文件:
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.user.sensor, PID: 8586 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.sensor.MainActivity.displayCleanValues(MainActivity.java:121) at com.example.user.sensor.MainActivity.onSensorChanged(MainActivity.java:100) at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:830) at android.os.MessageQueue.nativePollOnce(Native Method) at android.os.MessageQueue.next(MessageQueue.java:325) at android.os.Looper.loop(Looper.java:142) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
E / AndroidRuntime:致命例外:主进程:com.example.user.sensor,PID:8586 java.lang.NullPointerException:尝试在其上调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)' android.hardware.SystemSensorManager $ SensorEventQueue上com.example.user.sensor.MainActivity.onSensorChanged(MainActivity.java:100)处com.example.user.sensor.MainActivity.displayCleanValues(MainActivity.java:121)处的空对象引用.dispatchSensorEvent(SystemSensorManager.java:830)在android.os.MessageQueue.nativePollOnce(本机方法)在android.os.MessageQueue.next(MessageQueue.java:325)在android.os.Looper.loop(Looper.java:142) )的android.app.ActivityThread.main(ActivityThread.java:6494)的com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:438的java.lang.reflect.Method.invoke(本机方法) )在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
First, you need to provide an id of a TextView
in Layout file 首先,您需要在布局文件中提供
TextView
的ID
<TextView
android:id="@id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GYROSCOPE"
android:textColor="@android:color/black"
android:layout_marginTop="30dp"
/>
After that you need to declare the TextView
in java file see below code: 之后,您需要在Java文件中声明
TextView
,请参见以下代码:
TextView txt1, txt2;
after that in onCreate()
, initialize the TextView: 之后,在
onCreate()
,初始化TextView:
txt1 = (TextView) findViewById(R.id.txt1);// R.id.txt1 is a layout textbox ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.