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

(gtxtreme123) #1

Using a Format String


If CriminalIntent is already installed on your device, your existing database will not have the suspect
column, and your new onCreate(SQLiteDatabase) will not be run to add the new column, either.
As we said earlier, the easiest solution is to wipe out your old database in favor of a new one. (This
happens a lot in app development.)


First, uninstall the CriminalIntent app by opening the app launcher screen and dragging the
CriminalIntent icon to the top of the screen. All your sandbox storage will get blown away, along
with the out-of-date database schema, as part of the uninstall process. Next, run CriminalIntent from
Android Studio. A new database will be created with the new column as part of the app installation
process.


Using a Format String


The last preliminary step is to create a template crime report that can be configured with the specific
crime’s details. Because you will not know a crime’s details until runtime, you must use a format string
with placeholders that can be replaced at runtime. Here is the format string you will use:


%1$s! The crime was discovered on %2$s. %3$s, and %4$s

%1$s, %2$s, etc. are placeholders that expect string arguments. In code, you will call getString(...)
and pass in the format string and four other strings in the order in which they should replace the
placeholders.


First, in strings.xml, add the strings shown in Listing 15.7.


Listing 15.7  Adding string resources (strings.xml)


Choose Suspect
Send Crime Report
%1$s!
The crime was discovered on %2$s. %3$s, and %4$s

The case is solved
The case is not solved
there is no suspect.
the suspect is %s.
CriminalIntent Crime Report
Send crime report via
Free download pdf