user1256477
user1256477

Reputation: 11201

creating a database and default data

I would like to insert a default data in my sqlite database.

this is what i did:

private static final String DATABASE_CREATE_position = "CREATE TABLE position(latitude VARCHAR(20), longitude VARCHAR(20), address VARCHAR(100))";

@Override
public void onCreate(SQLiteDatabase db) {
    // Create the table
    db.execSQL(DATABASE_CREATE_position);   

    ContentValues defaultPos = new ContentValues();
    defaultPos.put("latitude", "40.604398");
    defaultPos.put("longitude", "-3.709002");
    defaultPos.put("address", "Avenida del parque ");   

    db.insert("position", null, defaultPos);

    db.close();

}

But the database is empty, where is the mistake?

Upvotes: 1

Views: 3095

Answers (2)

dmason82
dmason82

Reputation: 399

Get rid of the db.close() in your onCreate() function and it will insert just fine from the test code I wrote around yours. Otherwise it throws an IllegalStateException and states that the database isn't open.

Upvotes: 1

gezdy
gezdy

Reputation: 3322

solution :

private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {           
        db.execSQL(DATABASE_CREATE_position);

        db.execSQL("insert into position (latitude,longitude,address) values (40.604398,-3.709002,'Avenida del parque ')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    ....

Upvotes: 4

Related Questions