vendredi 6 mars 2015

onCreate() method of SQLiteHelper is never called

I'm creating a database in android using SQLite.


I wrote my code to create a table called products in onCreate() method.


Then when I call add() method to add some values into the table, I'm getting an error that there is no such table called products.


Here is my SQLiteHelper class :



public class MySQLiteHelper extends SQLiteOpenHelper {

//variable declarations and some code
...

@Override
public void onCreate(SQLiteDatabase db) {

// SQL statement to create a products table
String CREATE_PRODUCTS_TABLE = "CREATE TABLE TABLE_NAME ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT, " +
"title TEXT, " +
"price INTEGER )";

// create products table
db.execSQL(CREATE_PRODUCTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

// Create tables again
onCreate(db);
}

void add(String url, String title, String price) {
//some code
}


I read from a similar question that onCreate() is not a constructor and it is called only when database doesn't exist, but database doesn't exists in my case too, so why is it not called?


I also learnt that we need to call getWritableDatabase() or getReadableDatabase()


But I'm not sure where to make such a call in my code.


I tried to put the 'table creating code' which is in onCreate() in my add() method. For first run, I didn't get anything, but from the next time, I keep getting an error that 'a table already exists'.


Now, how can I ensure that table is created properly only once, before I call my add() method to insert some values. Any help please?


Aucun commentaire:

Enregistrer un commentaire