Android nullpointerexception

2019-05-24 06:17发布

问题:

To be 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 am receiving nullpointer exception at telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE); when I am removing the widget from the main screen.

What am I missing?

回答1:

context.getSystemService() may return null and you do not prove telephonyManager if it is null. If the name identified by Context.TELEPHONY_SERVICE does not exist in the system the telephonyManager will 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 the onDisabled Method you should initialize the telephonyManager. It smells like the onDisabled method is called somehow before onUpdate or if you have two different instances.



回答2:

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
        }

    };

}


回答3:

Just check telephonyManager to see if it is null.

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


回答4:

I got same probem. Actually problem disapeared after I made all null fields static. Looks like it;s really another instance of provider who gets onDisabled.