Android的NullPointerException异常 [英] Android nullpointerexception
问题描述
要短...我有一个小部件,你可以看到下面
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);
}
}
和我在收到空指针异常 telephonyManager.listen(监听器,PhoneStateListener.LISTEN_NONE);
当我从主屏幕删除小部件
and I am receiving nullpointer exception at telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
when I am removing the widget from the main screen.
我是什么失踪?
推荐答案
context.getSystemService()
可以返回空
你不能证明 telephonyManager
如果是空
。如果 Context.TELEPHONY_SERVICE
标识的名称不存在于系统中的 telephonyManager
将空
。
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
.
在除了您的评论:
@Override
public void onDisabled(Context context) {
if (telephonyManager!=null){
telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
}
super.onDisabled(context);
}
如果你需要运行在你应该初始化telephonyManager的 onDisabled
此方法code。它的气味像 onDisabled
方法之前,的onUpdate
莫名其妙地叫,或者如果你有两个不同的实例。
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.
这篇关于Android的NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!