2016-10-04 104 views
1

我使用listview创建一个appwidget。 在RemoteViewsFactory类我从SQLite数据库填充列表。一切都很好,但比我在RemoteViewsFactorygetViewAt方法得到IndexOutOfBoundsException异常如果我把一个字符串updateWidget()方法。为什么我在RemoteViewsFactory中获取IndexOutOfBoundsException?

它没有逻辑,为什么它会导致异常。因为在updateWidget()方法中,我只将文本设置为一个远程视图。

这里码列表和字符串,导致一个问题:

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) 
{ 
    SharedPreferences sPreferences = context.getSharedPreferences("WidgetSettings_"+appWidgetId,0); 
    RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.initial_layout); 
    DBHelper dbHelper = DBHelper.getInstance(context); 

    // To avoid Exception in a RemoteViewsFactory.getViewAt() method just comment or delete this line 
    rv.setTextViewText(R.id.textViewListTotal, "Total sum of items"); // this line cause an Exception. If I commenting it then all is OK 


    final Intent intent = new Intent(context, WidgetRemoteViewsService.class); 
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); 
    intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); 
    rv.setRemoteAdapter(appWidgetId, R.id.items_list, intent); 

    rv.setEmptyView(R.id.items_list, R.id.empty_view); 

    final Intent actionIntent = new Intent(context, WidgetProvider.class); 
    actionIntent.setAction(WidgetProvider.ACTION_MANAGE); 
    actionIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); 
    actionIntent.setData(Uri.parse(actionIntent.toUri(Intent.URI_INTENT_SCHEME))); 
    PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, actionIntent, 
      PendingIntent.FLAG_UPDATE_CURRENT); 
    rv.setPendingIntentTemplate(R.id.items_list, actionPendingIntent); 

    appWidgetManager.updateAppWidget(appWidgetId, rv); 
    appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.items_list); 
} 

回答

0

我与已知的解决方案做到了这一点。在getViewAt方法我贴一张支票声明是这样的:

@Override 
public RemoteViews getViewAt(int position) { 

    RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.list_item); 

    try { 
     if(ListItems.size() > 0) //<------- avoid indexoutofbound exception 
     { 
      // doing something with a remoteviews 
     } 
    } 
    catch (IndexOutOfBoundsException e) 
    { 
     e.printStackTrace(); 
    } 

    return rv; 
} 
+1

我不知道错误是什么。如果有人知道,请发布您的解决方案 – Trancer

相关问题