Search code examples
androidsqliteandroid-contentprovider

How to concatenate columns from a ContentProvider query?


I have a table that stores doctors in an Android SQLite database. I want to display the doctor's first name, last name, and suffix (MD, DDO, etc) in a ListView. Currently, I do so with the following query:

getContentResolver().query(
   DoctorEntry.CONTENT_URI,
   DOCTOR_COLUMNS, // Includes id, first name, last name, and suffix
   null,
   null,
   DoctorEntry.COLUMN_LASTNAME + " ASC, " + DoctorEntry.COLUMN_FIRSTNAME + " ASC");

Here is what DOCTOR_COLUMNS looks like:

private static final String[] DOCTOR_COLUMNS = {
        DoctorEntry.TABLE_NAME + "." + DoctorEntry._ID,
        DoctorEntry.COLUMN_FIRSTNAME,
        DoctorEntry.COLUMN_LASTNAME,
        DoctorEntry.COLUMN_SUFFIX
};

And then, in my adapter class I pull all the information and display it like this:

String firstName = cursor.getString(cursor.getColumnIndex(DoctorEntry.COLUMN_FIRSTNAME));
String lastName = cursor.getString(cursor.getColumnIndex(DoctorEntry.COLUMN_LASTNAME));
String suffix = cursor.getString(cursor.getColumnIndex(DoctorEntry.COLUMN_SUFFIX));

viewHolder.mTextView.setText(firstName + " " + lastName + ", " + suffix);

How can I adjust the projection parameter to concatenate each row so that I could simply say:

String fullName = cursor.getString(cursor.getColumnIndex(DoctorEntry.FULL_NAME));

Essentially, I'm looking for something like MySQL's CONCAT() function.


Solution

  • You can use the || operator to concatenate expressions:

    private static final String FULL_NAME = 
        DoctorEntry.COLUMN_FIRSTNAME + " || ' ' || "
        + DoctorEntry.COLUMN_LASTNAME + " || ', ' || "
        + DoctorEntry.COLUMN_SUFFIX;
    private static final String[] PROJECTION = { /* id column */, FULL_NAME };
    
    ...
    
    getContentResolver().query(
        DoctorEntry.CONTENT_URI,
        PROJECTION, // Includes id, first name, last name, and suffix
        null,
        null,
        DoctorEntry.COLUMN_LASTNAME + " ASC, " + DoctorEntry.COLUMN_FIRSTNAME + " ASC");
    
    ...
    
    String fullName = cursor.getString(cursor.getColumnIndex(FULL_NAME));