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:

<string name="crime_report">%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)

    <string name="crime_suspect_text">Choose Suspect</string>
    <string name="crime_report_text">Send Crime Report</string>
    <string name="crime_report">%1$s!
      The crime was discovered on %2$s. %3$s, and %4$s
    </string>
    <string name="crime_report_solved">The case is solved</string>
    <string name="crime_report_unsolved">The case is not solved</string>
    <string name="crime_report_no_suspect">there is no suspect.</string>
    <string name="crime_report_suspect">the suspect is %s.</string>
    <string name="crime_report_subject">CriminalIntent Crime Report</string>
    <string name="send_report">Send crime report via</string>
</resources>

In CrimeFragment.java, add a method that creates four strings and then pieces them together and returns a complete report.

Listing 15.8  Adding getCrimeReport() method (CrimeFragment.java)

    private void updateDate() {
        mDateButton.setText(mCrime.getDate().toString());
    }

    private String getCrimeReport() {
        String solvedString = null;
        if (mCrime.isSolved()) {
            solvedString = getString(R.string.crime_report_solved);
        } else {
            solvedString = getString(R.string.crime_report_unsolved);
        }

        String dateFormat = "EEE, MMM dd";
        String dateString = DateFormat.format(dateFormat,
                                              mCrime.getDate()).toString();

        String suspect = mCrime.getSuspect();
        if (suspect == null) {
            suspect = getString(R.string.crime_report_no_suspect);
        } else {
            suspect = getString(R.string.crime_report_suspect, suspect);
        }

        String report = getString(R.string.crime_report,
            mCrime.getTitle(), dateString, solvedString, suspect);

        return report;
    }
}

(Note that there are two DateFormat classes: android.text.format.DateFormat and java.text.DateFormat. Use android.text.format.DateFormat.)

Now the preliminaries are complete, and you can turn to implicit intents.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.0.25