Reputation: 6892
I'm using SQLite to create a database table for my app. I've searched online but haven't found the answer yet: Do I need to create a database first or is there a default database for each app?
I've written the following DBHelper class. It's in a separate file. How Do I call it when the app starts?
public class DataBaseHelper extends SQLiteOpenHelper{
final String CREAT_TABLE = "CREATE TABLE IF NOT EXIST `employee` ("+
"`id` int(11) NOT NULL AUTO_INCREMENT,"+
"`firstName` varchar(30) NOT NULL,"+
"`lastName` varchar(30) NOT NULL,"+
"PRIMARY KEY (`id`)"+
") ;";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREAT_TABLE);
}
}
Upvotes: 0
Views: 374
Reputation: 836
You don't have to create the database yourself. You specify the database name (the sqlite file name) when you call the superconstructor of your open helper. This will create or update the database with that name when needed (depending on which version number you send in vs. the current version number meta data).
I don't know what your constructor looks like but let's say it looks like
public DatabaseHelper(final Context context) {
super(context, "mydatabase", null, 0);
}
Then the SQLiteOpenHelper will create a database named "mydatabase" when you call getReadableDatabase() or getWritableDatabase(). It's all in the docs.
Upvotes: 2
Reputation: 2018
You declare your database name in the constructor
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
Upvotes: 1