You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CursorLoader读取Cursor时触发IndexOutOfBoundsException问题求助

Fixing IndexOutOfBoundsException with CursorLoader in Your Fragment

Let's break down why you're hitting this error and how to fix it clearly.

The Root Cause

Your crash happens at locations.get(0) in the onLoadFinished method. Here's the exact issue:

  • When your CursorLoader returns an empty Cursor (maybe there are no locations stored in your database yet, or the content provider query returned no results), cursor.moveToFirst() will return false.
  • This means your locations list stays completely empty, but you still try to access its first element with get(0)—which throws an IndexOutOfBoundsException because there's nothing to retrieve.

The Fix

You need to add a check for an empty locations list before trying to access its elements. Here's how to update your onLoadFinished method to handle this case:

@Override
public void onLoadFinished(Loader loader, Cursor data) {
    Log.d(TAG, "onLoadFinished: started");
    LocationsCursor cursor = new LocationsCursor(data);
    // Use generic type to avoid raw type warnings and make code safer
    List<String> locations = new ArrayList<>();
    
    if (cursor.moveToFirst()) {
        do {
            locations.add(cursor.getName());
        } while (cursor.moveToNext());
    }

    // Handle empty data case first to prevent crashes
    if (locations.isEmpty()) {
        // Disable the button to stop users from triggering invalid actions
        selectButton.setEnabled(false);
        Toast.makeText(getContext(), "No locations found in database", Toast.LENGTH_LONG).show();
        
        // Optional: Set a placeholder message for spinners
        List<String> placeholderList = Collections.singletonList("No locations available");
        ArrayAdapter<String> placeholderAdapter = new ArrayAdapter<>(
            getContext(), 
            android.R.layout.simple_expandable_list_item_1, 
            placeholderList
        );
        sourceSpinner.setAdapter(placeholderAdapter);
        destSpinner.setAdapter(placeholderAdapter);
        return;
    }

    // Only set defaults and adapters if we have valid data
    source = locations.get(0);
    destination = locations.get(0);
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(
        getContext(), 
        android.R.layout.simple_expandable_list_item_1, 
        locations
    );
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sourceSpinner.setAdapter(dataAdapter);
    destSpinner.setAdapter(dataAdapter);
}

Additional Tips to Avoid Future Issues

  1. Add Generic Types: I updated List locations to List<String> locations—this eliminates raw type warnings and ensures you're only adding string values to the list.
  2. Validate Data in Button Click: Even with the above fix, you might want to add an extra check in your onClick listener to ensure source and destination aren't empty or placeholder values.
  3. Verify Content Provider Setup: If you expect locations to exist, double-check that your LocationsColumns.CONTENT_URI is correct, your content provider is properly implemented, and that your database actually has location entries.

内容的提问来源于stack exchange,提问作者kaushal arora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:37:23