Yang Yang - 1 year ago 79
Android Question

Android app create table

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`)"+
") ;";

public void onCreate(SQLiteDatabase db) {

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download