Android Programming Tutorials

(Romina) #1
The Restaurant Store

import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;

class RestaurantHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="lunchlist.db";
private static final int SCHEMA_VERSION= 1 ;

public RestaurantHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
}

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

This says that our database name is lunchlist.db, we are using the first


version of the schema...and not much else. However, the project should still


compile cleanly after adding this class.


Step #2: Manage our Schema..............................................................


Next, we need to flesh out the onCreate() and onUpgrade() methods in


RestaurantHelper, to actually create the schema we want.


To do this, add an import for android.database.Cursor and use the following


implementation of onCreate():


@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT, address TEXT, type TEXT, notes TEXT);");
}

Here, we are simply executing a SQL statement to create a restaurant table


with a particular schema.


For onUpgrade(), there is nothing we really need to do now, since this


method will not be executed until we have at least two schema versions. So


94
Free download pdf