Somk
Somk

Reputation: 12047

Android Database

I'm trying to build a simple app to get to grips with android as I'm new. I have programmed for years in PHP and MySQL so it's not completely unfamiliar to me, but one concept is at the moment confusing to me.

If I wanted to create this app with 100's of questions how would I create the database like this. What I mean is at the moment my app runs and creates the database. Would I need to do this everytime the app runs as i'm guessing if it was a lot bigger it would mean a slow load evert time. Or is there a way to create the database once and then when the app runs there is no need to populate it.

Max

Upvotes: 0

Views: 445

Answers (3)

Rich
Rich

Reputation: 15757

Try creating a class that extends SQLLiteOpenHelper - there is a method called onCreate() which you can override:

private class DBOpenHelper extends SQLiteOpenHelper {

    public DBOpenHelper(Context context, String name, int version) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table ...");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // nothing to do
    }

}

You must then create a class that implements DatabaseHelper, and in its constructor instantiate the subclass of SQLLiteOpenHelper and call the establishDB() method:

public final class StandardSQLLiteDatabaseHelper implements DatabaseHelper {
    private SQLiteDatabase db;
private final DBOpenHelper openHelper;

StandardSQLLiteDatabaseHelper(final Context context) {
    this.openHelper = new DBOpenHelper(context, "MSPC", 1);
    if (db == null) {
        db = this.openHelper.getWritableDatabase();
    }
}
}

Upvotes: 0

chiranjib
chiranjib

Reputation: 5308

Steps

i>Install the Android mobile application & run

ii> Create the database & the table when the mobile application is executed for the first time

sample code:

sampleDB.openOrCreateDb(SplashScreen.this, DBConstants.DB_NAME,
                            MODE_PRIVATE, null);

Explanation:

When the mobile application is opened for the first time , the database is created & opened. Similarly the tables needs to be created as follows.

sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " + Constants.TABLE_NAME + " (Title VARCHAR, Description VARCHAR);");

From next time onwards when the mobile application is executed , only the database needs to be opened since its already created . The same applies for the tables too.

You can dump the 100 questions at the first time if you want , showing a progressdialog with proper message to indicate to the user that a background activity is being performed

Upvotes: 1

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181270

It's usually as you described. The SQLite database gets created (and perhaps populated) on the first application run. Then you just use the created database on subsequent runs.

Upvotes: 0

Related Questions