14.01.2013 Views

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6: Data Storage, Retrieval, and Sharing<br />

200<br />

}<br />

}<br />

int newVersion) {<br />

Log.w(TAG, “Upgrading database from version “ + oldVersion + “ to “<br />

+ newVersion + “, which will destroy all old data”);<br />

db.execSQL(“DROP TABLE IF EXISTS “ + EARTHQUAKE_TABLE);<br />

onCreate(db);<br />

4. Create a UriMatcher to handle requests using different URIs. Include support for queries and<br />

transactions over the entire data set (QUAKES) and a single record matching a quake index value<br />

(QUAKE_ID).<br />

// Create the constants used to differentiate between the different URI<br />

// requests.<br />

private static final int QUAKES = 1;<br />

private static final int QUAKE_ID = 2;<br />

private static final UriMatcher uriMatcher;<br />

// Allocate the UriMatcher object, where a URI ending in ‘earthquakes’<br />

// will correspond to a request for all earthquakes, and ‘earthquakes’<br />

// with a trailing ‘/[rowID]’ will represent a single earthquake row.<br />

static {<br />

uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);<br />

uriMatcher.addURI(“com.paad.provider.Earthquake”, “earthquakes”,<br />

QUAKES);<br />

uriMatcher.addURI(“com.paad.provider.Earthquake”, “earthquakes/#”,<br />

QUAKE_ID);<br />

}<br />

5. Override the getType method to return a String for each of the URI structures supported.<br />

@Override<br />

public String getType(Uri uri) {<br />

switch (uriMatcher.match(uri)) {<br />

case QUAKES:<br />

return “vnd.android.cursor.dir/vnd.paad.earthquake”;<br />

case QUAKE_ID:<br />

return “vnd.android.cursor.item/vnd.paad.earthquake”;<br />

default:<br />

throw new IllegalArgumentException(“Unsupported URI: “ + uri);<br />

}<br />

}<br />

6. Override the provider’s onCreate handler to create a new instance of the database helper class<br />

and open a connection to the database.<br />

@Override<br />

public boolean onCreate() {<br />

Context context = getContext();<br />

earthquakeDatabaseHelper dbHelper;<br />

dbHelper = new earthquakeDatabaseHelper(context, DATABASE_NAME, null,<br />

DATABASE_VERSION);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!