Joe Eigi
Joe Eigi

Reputation: 1051

Inserting rows into table only once in Android Database

I want to only insert like 10 rows into a table at database creation. I do not want them added every time the app is open. Just once as a table with final values. How would I go about doing this? Thanks!

public void insertEvents(){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(COL_EVENT, "value1");
    values.put(COL_EVENT, "value2");
    values.put(COL_EVENT, "value3");
    values.put(COL_EVENT, "value4");

    db.insert(TABLE_EVENTS, null, values);
}

Upvotes: 0

Views: 1899

Answers (3)

remykarem
remykarem

Reputation: 2469

I know this might be too late but I'm just sharing my answers. Your code seems to show that you are trying to add 4 rows. Here are some pointers:

1) Do it in the onCreate method, as mentioned by @Georgiy Shur.

2) The insert method only inserts one row at a time. So you should do this instead:

ContentValues values = new ContentValues();
values.put(COL_EVENT, "value1");
db.insert(TABLE_EVENTS, null, values);
values.put(COL_EVENT, "value2");
db.insert(TABLE_EVENTS, null, values);
values.put(COL_EVENT, "value3");
db.insert(TABLE_EVENTS, null, values);
values.put(COL_EVENT, "value4");
db.insert(TABLE_EVENTS, null, values);

Upvotes: 0

Georgiy Shur
Georgiy Shur

Reputation: 840

Do it in onCreate method of DatabaseHelper

EDIT: here is the similar question. Or you can try this tutorial

Upvotes: 1

laalto
laalto

Reputation: 152817

Since you are using SQLiteOpenHelper, put the inserts in its onCreate(). Use the SQLiteDatabase passed in as argument, do not recursively call getWritableDatabase().

Upvotes: 1

Related Questions