Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.StringIndexOutOfBoundsException: index=0 length=0 in get sqlite database

I am trying to open a writeable SQLite database with this code...

public DataAdapterForServieClass open() throws SQLException {
    db = DBHelper.getWritableDatabase();
    return this;
}

However I am getting the following error on the db = DBHelper.getWritableDatabase(); line...

06-10 11:58:13.995: ERROR/AndroidRuntime(548): FATAL EXCEPTION: main
06-10 11:58:13.995: ERROR/AndroidRuntime(548): java.lang.StringIndexOutOfBoundsException: index=0 length=0
06-10 11:58:13.995: ERROR/AndroidRuntime(548):     at android.app.ContextImpl.validateFilePath(ContextImpl.java:1518)
06-10 11:58:13.995: ERROR/AndroidRuntime(548):     at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:725)
06-10 11:58:13.995: ERROR/AndroidRuntime(548):     at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221)
06-10 11:58:13.995: ERROR/AndroidRuntime(548):     at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:149)

This is the code of my DBHelper class...

static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion 
            + " to "
            + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS titles");
        onCreate(db);
    }

    public void onCreate(SQLiteDatabase arg0) {
        // TODO Auto-generated method stub
    }
}   

Could someone please help me.

like image 479
Kishor datta gupta Avatar asked Nov 04 '22 22:11

Kishor datta gupta


1 Answers

When you call getWritableDatabase() for the first time, it will call the following methods, according to the Android Documentation...

onCreate(SQLiteDatabase)
onUpgrade(SQLiteDatabase, int, int)
onOpen(SQLiteDatabase)

You don't have any code in your onCreate() method - you'll need to do something here before it will work, such as this...

public void onCreate(SQLiteDatabase database) {
    database.openOrCreateDatabase("/come/example/mydatabase",null);
}

Look at the checkDataBase() method in the link you posted where it calls openDatabase() - this does the same thing, and is the important piece of code that you're missing. You need to create the database before you can do anything with it.

Also make sure that somewhere in your code you are creating your DBHelper instance, so that it calls the super() method. Like this...

DBHelper helper = new DatabaseHelper(context);
like image 182
wattostudios Avatar answered Nov 09 '22 12:11

wattostudios