我想在光传感器上进行活动,但恢复方法显示错误。
package com.example.user.projectandroid;
import android.app.Activity;
import android.app.Service;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
public class pushup extends Activity implements SensorEventListener{
SensorManager sensorManager;
Sensor sensor;
EditText ed;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("myn", "onCreate: ");
setContentView(R.layout.ushup);
ed=(EditText)findViewById(R.id.editText8);
SensorManager sensorManager=
(SensorManager)getSystemService(Service.SENSOR_SERVICE);
sensor=sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}
protected void onPause(){
super.onPause();
Log.d("myn", "onpause: ");
sensorManager.unregisterListener(this);
}
protected void onResume(){
super.onResume();
sensorManager.registerListener(this,sensor,
SensorManager.SENSOR_DELAY_NORMAL);//error
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
Log.d("myn", "onSensorChanged: ");
if(sensorEvent.sensor.getType()==Sensor.TYPE_LIGHT)
ed.setText(""+sensorEvent.values[0]);
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}
错误是
java.lang.NullPointerException:尝试在空对象引用上调用虚方法'boolean android.hardware.SensorManager.registerListener(android.hardware.SensorEventListener,android.hardware.Sensor,int)'
答案 0 :(得分:1)
好的,我可以看到问题是你已经两次声明了SensorManager's
个对象,因此导致NullPointerException
。尝试从下面描述的行中删除SensorManager
并将其更正为:
sensorManager = (SensorManager)getSystemService(Service.SENSOR_SERVICE);
希望它有所帮助...