2013-03-10 99 views
1

在我的活動中,我有一個名爲「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)上測試我的應用程序 我錯了什麼?謝謝:)

回答

0

做到這一點

tv = (TextView)findViewById(R.id.senzosv); 

setContentView()

+0

謝謝。它現在運作良好。我還有一個問題。光線傳感器能夠僅返回值1000,100和10嗎?或者它可以更準確嗎?謝謝 – 2013-03-10 11:03:34

+0

如果這解決了你的問題接受回答 – DjHacktorReborn 2013-03-10 11:04:22

0

必須調用setContentView(R.layout.layout_main);因爲它的設置,則活動佈局得到TextView的參考。

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.layout_main); 
    tv = (TextView)findViewById(R.id.senzosv); 
} 

是光傳感器能夠只返回值1000,100和10?

直接從系統設備文件

Scanner st = new Scanner(new File("/sys/devices/virtual/lightsensor/switch_cmd/lightsensor_file_state")); 
int lux = st.nextInt(); 
st.close(); 
+0

謝謝,但是如果我想要實時讀取該值,我應該在哪裏放這個代碼? – 2013-03-10 21:49:43

+0

@MartinNemeth你可以把它放在服務中... – 2013-03-11 04:36:31

0

您只能使用findViewById你有setContentView後得到的值。

即它移動到onCreatesetContentView

TextView tv; 

public void onCreate(Bundle b){ 
    super.onCreate(b); 
    setContentView(R.layout.activity_main); 

    tv = (TextView) findViewById(R.id.senzosv); 

} 

如果你讀你的logcat多一點小心地將解釋什麼行代碼是導致空指針,你可以調試更方便。


您還需要清單中的權限才能使用傳感器。

+0

有沒有一種方法可以讓我的光線傳感器更精確?它只顯示10,100或1000個值。 – 2013-03-10 11:30:34