I'm extending the SQLiteOpenHelper class to help me connect and do my database work. According to the documentation, the OnCreate method should only be called if the database has not been created. Yet, my problem is that I am getting this error when I try to execute a query to insert a record.
ERROR/Database(214): Failure 1 (table Sample already exists) on 0x218688 when preparing
'CREATE TABLE Sample (RecId INT, SampleDesc TEXT);'.
The only place this Create query is used in code is the OnCreate meth开发者_JAVA技巧od which looks like this.
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SAMPLE_TABLE_CREATE);
}
Note: I'm following a tutorial - the only thing I've done different is make the SQLiteDatabase object public instead of private so that I could extend this class for each entity, letting the public SQLiteDatabase object from the inherited DataHelper class do all the work
Here is the method that makes the call that fails.
//This method is in the class that extends DataHelper (See note on tutorial)
public void createSample(Sample sample)//next action form
{
String id = sample.getId();
String name = sample.getSummary();
String query = "INSERT INTO " + SAMPLE_TABLE_NAME + "( " + SAMPLE_Id + "," +
SAMPLE_NAME + ") " + " VALUES (" + id + "," + name + ")";
try{
data.rawQuery(query, null);
}
catch(SQLException e){
Log.i("Sample", "Errors: Sample LN60: " + e.getMessage());
}
}
Can someone tell me what I'm doing wrong? Or maybe a hack (i.e. check if table exists before executing create statement)
Please let me know what other code I can post to solve this...
Is it due to you've execute it your activity once and never destroy the DB after that? And 2nd run you'd hit this error.
Database is stored in /data/data/YOUR_PACKAGE/databases/
, so a workaround would be to check if the DB exists here before creating it.
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
private static String DB_NAME = "myDBName";
SQLiteDatabase checkDB = null;
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
if(checkDB){
//do nothing
}else{
//create DB
}
Code source here
The first error is quite simply because you are creating a table that already exists, so yes adding a check if the table exists prior to creating it would be good. Once an SQLite dB is created or made it will stay until someone or something deletes it, unlike the default onCreate() call which resembles re-creating or drawing your screen.
every time you call getWritableDatabase() onCreate() method is called.
精彩评论