Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Inserting and updating rows


Inserting and updating rows


Now that you have a ContentValues, it is time to add rows to the database. Fill out addCrime(Crime)
with a new implementation.


Listing 14.9  Inserting a row (CrimeLab.java)


public void addCrime(Crime c) {
ContentValues values = getContentValues(c);


mDatabase.insert(CrimeTable.NAME, null, values);
}


The insert(String, String, ContentValues) method has two important arguments and one that is
rarely used. The first argument is the table you want to insert into – here, CrimeTable.NAME. The last
argument is the data you want to put in.


And the second argument? The second argument is called nullColumnHack. And what does it do?


Well, say that you decided to call insert(...) with an empty ContentValues. SQLite does not allow
this, so your insert(...) call would fail.


If you passed in a value of uuid for nullColumnHack, though, it would ignore that empty
ContentValues. Instead, it would pass in a ContentValues with uuid set to null. This would allow
your insert(...) to succeed and create a new row.


Handy? Perhaps someday. Not today, though. Now you know about it, at least.


Continue applying ContentValues by writing a method to update rows in the database.


Listing 14.10  Updating a Crime (CrimeLab.java)


public Crime getCrime(UUID id) {
return null;
}


public void updateCrime(Crime crime) {
String uuidString = crime.getId().toString();
ContentValues values = getContentValues(crime);


mDatabase.update(CrimeTable.NAME, values,
CrimeTable.Cols.UUID + " = ?",
new String[] { uuidString });
}


private static ContentValues getContentValues(Crime crime) {


The update(String, ContentValues, String, String[]) method starts off similarly to insert(...)



  • you pass in the table name you want to update and the ContentValues you want to assign to each
    row you update. However, the last bit is different, because now you have to specify which rows get
    updated. You do that by building a where clause (the third argument) and then specifying values for the
    arguments in the where clause (the final String[] array).

Free download pdf