java - 为什么我在 RemoteViewsFactory 中收到 IndexOutOfBoundsException?

标签 java listview android-appwidget android-remoteview

我创建了一个带有 ListView 的应用程序小部件。 在 RemoteViewsFactory 类中,我从 SQLite 数据库填充列表。一切都很好,但是如果我在 updateWidget() 方法中放入一个字符串,那么我会在 RemoteViewsFactorygetViewAt 方法中得到 IndexOutOfBoundsException

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

这里是导致问题的代码列表和字符串:

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);
}

最佳答案

我使用已知的解决方案完成了此操作。在 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;
}

关于java - 为什么我在 RemoteViewsFactory 中收到 IndexOutOfBoundsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851179/

相关文章:

java - 查找 startAngle 和 arcAngle 传递给 Java Graphics 的 drawArc()

java - 如何减少Java中的日志记录频率?

android - 滚动时 ListView 的奇怪行为

android - App Widget 上的 Marquee TextView

java - 我可以在代码的静态部分使用谷歌反射来查找子类吗?

java - 需要帮助在 selenium webdriver 新打开的窗口中查找文本框

WPF ListView RAM 大幅增加

android - Android中从数据库填充ListView

android - 计算appwidget的高度

java - 用于 AppWidget 更新的 IntentService 罕见崩溃