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

如何解决Android Studio中SQLite引发的StringIndexOutOfBoundsException异常

Fixing StringIndexOutOfBoundsException When Opening SQLite Database in Android Studio

Hey there! Let's break down why your app is crashing when trying to access the SQLite database and how to fix it.

What's Causing the Crash?

Looking at your error stack trace, the key culprit line is:

java.lang.StringIndexOutOfBoundsException: length=0; index=0
at java.lang.String.charAt(Native Method)
at android.app.ContextImpl.validateFilePath(ContextImpl.java:1926)

This happens because Android is trying to validate the file path for your database, but the database name you provided is an empty string. When the system tries to check the first character of an empty string with charAt(0), it throws this exception—directly leading to the crash when you call getReadableDatabase().

Step-by-Step Fixes

1. Fix Your PetDbHelper Class

The issue is almost certainly in your SQLiteOpenHelper subclass (likely PetDbHelper). Make sure you're passing a non-empty, valid database name in its constructor.

Here's how your helper class should look:

public class PetDbHelper extends SQLiteOpenHelper {
    // Critical: Use a non-empty database name (this fixes the crash!)
    private static final String DATABASE_NAME = "pets.db";
    private static final int DATABASE_VERSION = 1;

    public PetDbHelper(Context context) {
        // Pass the valid database name here
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // Your table creation SQL (add this if you haven't already)
        String SQL_CREATE_PETS_TABLE = "CREATE TABLE " + PetContract.PetEntry.TABLE_NAME + " ("
                + PetContract.PetEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + PetContract.PetEntry.COLUMN_PET_NAME + " TEXT NOT NULL, "
                + PetContract.PetEntry.COLUMN_PET_BREED + " TEXT, "
                + PetContract.PetEntry.COLUMN_PET_GENDER + " INTEGER NOT NULL, "
                + PetContract.PetEntry.COLUMN_PET_WEIGHT + " INTEGER NOT NULL DEFAULT 0);";
        db.execSQL(SQL_CREATE_PETS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Handle database upgrades if needed
        db.execSQL("DROP TABLE IF EXISTS " + PetContract.PetEntry.TABLE_NAME);
        onCreate(db);
    }
}

Double-check that DATABASE_NAME is not an empty string ("") or null—this is the root cause of your crash.

2. Verify PetDbHelper Initialization in CatalogActivity

Make sure you're initializing mPetDbHelper correctly with a valid context:

private PetDbHelper mPetDbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_catalog);
    // Initialize the helper with the activity's context
    mPetDbHelper = new PetDbHelper(this);
}

3. Fix a Potential Cursor Issue (Bonus Best Practice)

Looking at your displayDatabaseInfo() method, there's a small problem with how you handle the cursor:

  • You declare Cursor cursor outside the try-with-resources block, but initialize it inside. When the try block ends, SQLiteDatabase db gets closed, which invalidates the cursor and could lead to future crashes.

Here's the corrected version using try-with-resources for both the database and cursor:

private void displayDatabaseInfo() {
    String[] projection = {
            PetContract.PetEntry._ID,
            PetContract.PetEntry.COLUMN_PET_NAME,
            PetContract.PetEntry.COLUMN_PET_BREED,
            PetContract.PetEntry.COLUMN_PET_GENDER,
            PetContract.PetEntry.COLUMN_PET_WEIGHT
    };

    // Auto-close both db and cursor with try-with-resources
    try (SQLiteDatabase db = mPetDbHelper.getReadableDatabase();
         Cursor cursor = db.query(PetContract.PetEntry.TABLE_NAME, projection, null, null, null, null, null)) {

        TextView displayView = findViewById(R.id.text_view_pet);
        // Display cursor count and column headers
        displayView.setText("The pets table contains: " + cursor.getCount() + " pets.\n\n");
        displayView.append(PetContract.PetEntry._ID + " - "
                + PetContract.PetEntry.COLUMN_PET_NAME + " - "
                + PetContract.PetEntry.COLUMN_PET_BREED + " - "
                + PetContract.PetEntry.COLUMN_PET_GENDER + " - "
                + PetContract.PetEntry.COLUMN_PET_WEIGHT);

        // Get column indices
        int idColumnIndex = cursor.getColumnIndex(PetContract.PetEntry._ID);
        int nameColumnIndex = cursor.getColumnIndex(PetContract.PetEntry.COLUMN_PET_NAME);
        int breedColumnIndex = cursor.getColumnIndex(PetContract.PetEntry.COLUMN_PET_BREED);
        int genderColumnIndex = cursor.getColumnIndex(PetContract.PetEntry.COLUMN_PET_GENDER);
        int weightColumnIndex = cursor.getColumnIndex(PetContract.PetEntry.COLUMN_PET_WEIGHT);

        // Iterate through cursor rows
        while (cursor.moveToNext()) {
            int currentID = cursor.getInt(idColumnIndex);
            String currentName = cursor.getString(nameColumnIndex);
            String currentBreed = cursor.getString(breedColumnIndex);
            int currentGender = cursor.getInt(genderColumnIndex);
            int currentWeight = cursor.getInt(weightColumnIndex);

            displayView.append("\n" + currentID + " - "
                    + currentName + " - "
                    + currentBreed + " - "
                    + currentGender + " - "
                    + currentWeight);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This removes the need for a separate finally block and ensures resources are properly cleaned up.

Final Notes

Once you fix the empty database name in PetDbHelper, the StringIndexOutOfBoundsException should disappear immediately. The cursor fix is just a best practice to avoid future issues.

内容的提问来源于stack exchange,提问作者nidhi chaudhary

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:51:45