Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add initial data to SQLite database?

I need to add initial values to SQLite database, once application is started first time. How should I do it?

like image 819
LA_ Avatar asked May 21 '11 09:05

LA_


3 Answers

In DBAdapter.java class file you can do that.


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_1);
        db.execSQL(CREATE_TABLE_2);
        db.execSQL(CREATE_TABLE_3);
        db.execSQL("insert into " + DATABASE_TABLE3 + "(" + KEY_ROWID + ","
                + KEY_DEF + ") values(1,'')");
    }

Like this type.

like image 198
Nikhil Avatar answered Oct 07 '22 10:10

Nikhil


In case you are using org.droidparts library OR-Mapper for accessing your database you can do it like this.

In your implementation of

public class CategoryEntityMgr extends EntityManager<Category> {
    public CategoryEntityMgr(Context ctx) {
        super(Category.class, ctx);
    }

    // NEW --> this one must be used in onCreateTables or you will receive a database locked exception
    private CategoryEntityMgr(Context ctx, SQLiteDatabase db) {
        super(Category.class, ctx, db);
    }
}

In your implementation of AbstractDbOpenHelper:

protected void onCreateTables(SQLiteDatabase db) {
    // create your tables as usual
    createTables(db, Booking.class, Category.class);

    // Use a new instance of your entity manager
    //    but use the 2nd constructor to provide the db connection
    CategoryEntityMgr mgr = new CategoryEntityMgr(ctx, db);

    // add the new table row / entity you an to have
    Category c = new Category();
    c.name = "the value for this column";
    mgr.createOrUpdate(c);
}
like image 31
turtletramp Avatar answered Oct 07 '22 11:10

turtletramp


One time or first-load requirements like this are common.

1) Set a flag variable named FIRSTLOAD and set it to True. Be sure to save this variable to isolated storage in the device to read back each time the application is started. 2) Create a method which checks the value of FIRSTLOAD and only executes if FIRSTLOAD is true. Place your code which 'add[s] initial values to SQLite database' here. Then set the FIRSTLOAD variable to false. This way it will only execute the code once!

Boolean FIRSTLOAD= new Boolean("true");

void SetInitialValues()
{
   if(!FIRSTLOAD)
      return;

   // insert your code to run only when application is started first time here


   FIRSTLOAD = False;
}
like image 31
dev4life Avatar answered Oct 07 '22 12:10

dev4life