Android nullpointerexception

In short ... I have a widget, you can see the important part below

public class ExampleWidget extends AppWidgetProvider {
private PhoneStateListener listener;
private TelephonyManager telephonyManager;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {

    listener = new PhoneStateListener() {
        @Override
        public void onDataConnectionStateChanged(int state) {
            // removed the code
        }

    };

    telephonyManager = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(listener,
            PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);

}

@Override
public void onDisabled(Context context) {
    telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
    super.onDisabled(context);
}
}

and I get a nullpointer exception telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);when I remove the widget from the main screen.

What am I missing?

+2
source share
4 answers

context.getSystemService()can return null, and you will not prove telephonyManagerif it is null. If the name identified Context.TELEPHONY_SERVICEdoes not exist in the system, there telephonyManagerwill be null.

In addition to your comment:

@Override
public void onDisabled(Context context) {
    if (telephonyManager!=null){
        telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
    }
    super.onDisabled(context);
}

If you need to run this code in a method onDisabled, you must initialize the telephonyManager. It smells like the method onDisabledis called somehow before onUpdateor if you have two different instances.

+2
source
public class ExampleWidget extends AppWidgetProvider {
private PhoneStateListener listener;
private TelephonyManager telephonyManager;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {


    telephonyManager = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(listener,
            PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);

}

@Override
public void onDisabled(Context context) {
    telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
    super.onDisabled(context);
}
listener = new PhoneStateListener() {
        @Override
        public void onDataConnectionStateChanged(int state) {
            // removed the code
        }

    };

}
0

Just check telephonyManagerto see if it is null.

if(telephonyManager==null){
    telephonyManager = (TelephonyManager) context
        .getSystemService(Context.TELEPHONY_SERVICE);
}
telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
0
source

I have the same problem. In fact, the problem disappeared after I made all empty fields static. It looks like this is really a different provider instance that gets onDisabled.

0
source

All Articles