Skip to content Skip to sidebar Skip to footer

My Application Crashes When I Register A Sensor Listener

In Android I am creating a Service, which will listen for sensor value change. But my application keeps crashing whenever I open it. If I remove the Lines sensorManager = (Sensor

Solution 1:

mContext is null - you need to initialise it before you pass it to Toast.makeText().

Service is a context so you can just call

Toast.makeText(this,"Heelooo" , Toast.LENGTH_SHORT).show(); 

It works when you remove the lines you mention because then the SensorListener is never registered, and onSensorChanged is never called.


Solution 2:

In CustomSensorService class : Inside onSensorChanged() method: You used mContext variable value without initializing it.

Your code: Toast.makeText(mContext,"Heelooo" , Toast.LENGTH_SHORT).show();

Changes to be done to resolve this issue:

Toast.makeText(this, "Heelooo", Toast.LENGTH_SHORT).show();

Due to the above reason you are getting NullPointerException while displaying toast.


Post a Comment for "My Application Crashes When I Register A Sensor Listener"