在我的活動中,我有一個名爲「senzosv」的TextView。我希望它能顯示我的光線傳感器的當前值。我有以下代碼。android:光傳感器nullPointerException
public class Osvetlenie extends Activity implements OnItemSelectedListener, OnSeekBarChangeListener, SensorEventListener {
SensorManager sm;
Sensor proxSensor;
Sensor lighhtSens;
TextView tv = (TextView)findViewById(R.id.senzosv);
這是我的onCreate:
...
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
proxSensor =sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
lighhtSens = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
sm.registerListener(this, proxSensor, SensorManager.SENSOR_DELAY_NORMAL);
sm.registerListener(this, lighhtSens, SensorManager.SENSOR_DELAY_NORMAL);
這裏有方法onSensorChanged和onAccuracyChanged
public void onSensorChanged(SensorEvent event)
{
if(event.sensor.getType() == Sensor.TYPE_LIGHT)
{
tv.setText("value: " + event.values[0] + " lux");
Toast.makeText(getApplicationContext(),"On SensorChanged"+ event.values[0],Toast.LENGTH_SHORT).show();
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(ACCESSIBILITY_SERVICE,"onAccuracyChanged: " + sensor + ", accuracy: " + accuracy);
if(sensor.getType() == Sensor.TYPE_LIGHT){
Log.i("Sensor Changed", "Accuracy :" + accuracy);
}
}
當我運行我的應用程序,當我試圖啓動這一活動, LogCat中出現nullpointexception,錯誤消息:應用程序意外關閉 我在Samsung Galaxy S II(GT-I9100)上測試我的應用程序 我錯了什麼?謝謝:)
謝謝。它現在運作良好。我還有一個問題。光線傳感器能夠僅返回值1000,100和10嗎?或者它可以更準確嗎?謝謝 – 2013-03-10 11:03:34
如果這解決了你的問題接受回答 – DjHacktorReborn 2013-03-10 11:04:22