jeudi 7 mai 2015

SQLiteOpenHelper - Where do I store initial data?

I have some initial data to insert in my database. I've added it to my custom SQLiteOpenHelper class.

package com.company.database;

import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    public static final String TABLE_NAMES = "names";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "name";

    private static final String DATABASE_NAME = "my.db";
    private static final int DATABASE_VERSION = 1;

    private static final String TABLE_NAMES_CREATE = "CREATE TABLE " + TABLE_NAMES + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_NAME + " VARCHAR NOT NULL);";

    private static final String TABLE_NAMES_INSERT = "INSERT INTO " + TABLE_NAMES
            + "(" + COLUMN_NAME + ")" + " VALUES "
            + "('Antony'),"
            + "('Benny'),"
            + "('Carol'),"
            + "('Daniel'),"
            // ... AND SO ON ...

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

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(TABLE_NAMES_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
        dropTable(database);
        onCreate(database);
    }

    private void dropTable(SQLiteDatabase database) {
        database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAMES);
    } }

Please note the insert statements. The quantity of names will increase and i don't want to keep this mess.

What should i do to fix it?

Aucun commentaire:

Enregistrer un commentaire