Android Programming Tutorials

(Romina) #1
Asking Permission to Place a Call

db.execSQL("CREATE TABLE restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT, address TEXT, type TEXT, notes TEXT, phone TEXT);");
}

Any time you make a material modification to the schema, you also need to


increment the schema version number. For RestaurantHelper, that is held in


SCHEMA_VERSION, so increment to 2 :


private static final int SCHEMA_VERSION= 2 ;

Step #2: Intelligently Handle Database Updates.............................


When the schema version increments, onUpgrade() is called on


RestaurantHelper rather than onCreate(). It is our job to update the schema,


preferably without losing any user data. Here, we just use an ALTER TABLE


SQL statement, since all we are doing is adding a column:


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion== 1 && newVersion== 2 ) {
db.execSQL("ALTER TABLE restaurants ADD phone TEXT;");
}
}

Step #3: Add Phone Number Support to the Rest of the Helper...


the Helper


We also need to update our insert() method on RestaurantHelper to accept


a phone number:


public void insert(String name, String address,
String type, String notes,
String phone) {
ContentValues cv=new ContentValues();

cv.put("name", name);
cv.put("address", address);
cv.put("type", type);
cv.put("notes", notes);
cv.put("phone", phone);

getWritableDatabase().insert("restaurants", "name", cv);
}

340
Free download pdf