我得到NullPointerException
(有时),我的appwidget崩溃了。
它适用于任何远程视图setTextViewText
。
我已经检查了我想要设置的值,它绝对不是空的。
以下是代码段:
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase(UPDATE)){
ComponentName thisWidget = new ComponentName(context, abc.class);
try
{
String currentDay = todayDay();
String current = todayDate();
System.out.println("On Receive : " + R.id.day + currentDay);
views.setTextViewText(R.id.day, currentDay);
views.setTextViewText(R.id.date, current);
performUpdate(context);
}
catch(NullPointerException e)
{
e.printStackTrace();
}
AppWidgetManager manager = AppWidgetManager.getInstance(context);
//update widget
manager.updateAppWidget(thisWidget, views);
}
}
public static String todayDay(){
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
String dayToReturn="";
switch(day){
case 1: dayToReturn = "Sunday";
break;
case 2: dayToReturn = "Monday";
break;
case 3: dayToReturn = "Tuesday";
break;
case 4: dayToReturn = "Wednesday";
break;
case 5: dayToReturn = "Thursday";
break;
case 6: dayToReturn = "Friday";
break;
case 7: dayToReturn = "Saturday";
break;
}
return dayToReturn;
}
Logcat错误:
01-04 14:38:32.055: W/System.err(26368): java.lang.NullPointerException
01-04 14:38:32.060: W/System.err(26368): at com.appwidgets.abc.onReceive(abc.java:167)
01-04 14:38:32.060: W/System.err(26368): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2133)
01-04 14:38:32.060: W/System.err(26368): at android.app.ActivityThread.access$1500(ActivityThread.java:128)
01-04 14:38:32.060: W/System.err(26368): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1211)
01-04 14:38:32.060: W/System.err(26368): at android.os.Handler.dispatchMessage(Handler.java:99)
01-04 14:38:32.060: W/System.err(26368): at android.os.Looper.loop(Looper.java:137)
01-04 14:38:32.060: W/System.err(26368): at android.app.ActivityThread.main(ActivityThread.java:4514)
01-04 14:38:32.060: W/System.err(26368): at java.lang.reflect.Method.invokeNative(Native Method)
01-04 14:38:32.060: W/System.err(26368): at java.lang.reflect.Method.invoke(Method.java:511)
01-04 14:38:32.060: W/System.err(26368): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
01-04 14:38:32.060: W/System.err(26368): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
01-04 14:38:32.060: W/System.err(26368): at dalvik.system.NativeStart.main(Native Method)
虽然我已经添加了try catch block以避免这种情况,但它没有帮助。 同样的问题只是出现了。 非常感谢任何帮助:)
答案 0 :(得分:0)
调用remoteViews.setTextViewText后,您需要通过调用updateAppWidget来更新窗口小部件。
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, remoteViews);