do this
tv = (TextView)findViewById(R.id.senzosv);
after setContentView()
Frage
In my activity I have one TextView called "senzosv". I want it to show current value from my light sensor. I have following code.
public class Osvetlenie extends Activity implements OnItemSelectedListener, OnSeekBarChangeListener, SensorEventListener {
SensorManager sm;
Sensor proxSensor;
Sensor lighhtSens;
TextView tv = (TextView)findViewById(R.id.senzosv);
This is in my 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);
And here are methods onSensorChanged and 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);
}
}
When I run my application, and when I am trying to start this activity, I get nullpointexception in LogCat and error message: application unexpectedly closed I am testing my app on Samsung Galaxy S II (GT-I9100) What did I wrong? Thank you :)
Lösung
do this
tv = (TextView)findViewById(R.id.senzosv);
after setContentView()
Andere Tipps
You can only use findViewById
after you have setContentView
.
i.e. move it into onCreate
after setContentView
TextView tv;
public void onCreate(Bundle b){
super.onCreate(b);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.senzosv);
}
If you read your LogCat a bit more carefully it will explain what line of your code is causing the NullPointer and you could debug it easier.
You will also need permissions in your manifest to use the sensor.
You must call setContentView(R.layout.layout_main);
because Its set the activity layout then get the textview reference.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
tv = (TextView)findViewById(R.id.senzosv);
}
Is light sensor able to return only values 1000, 100 and 10?
Directly get value from the system device file
Scanner st = new Scanner(new File("/sys/devices/virtual/lightsensor/switch_cmd/lightsensor_file_state"));
int lux = st.nextInt();
st.close();