如何连接 ContentProvider 查询中的列?

How to concatenate columns from a ContentProvider query?

我有一个 table 将医生存储在 Android SQLite 数据库中。我想在 ListView 中显示医生的名字、姓氏和后缀(MD、DDO 等)。目前,我使用以下查询来执行此操作:

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");

这是 DOCTOR_COLUMNS 的样子:

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

然后,在我的适配器中 class 我提取所有信息并像这样显示:

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);

如何调整 projection 参数以连接每一行,以便我可以简单地说:

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

本质上,我正在寻找类似 MySQL 的 CONCAT() 函数的东西。

您可以使用 || 运算符连接表达式:

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));