如何将从数据库中获取的结果转换为单个字符串?

时间:2015-05-20 22:37:17

标签: java

我有从数据库中提取标签的代码:

public void fetchTags() {  
        ContentResolver contentResolver = this.getContentResolver();  
        Cursor cursor = contentResolver.query(TagsContentProvider.CONTENT_URI,  
                 new String[]{Tags.COLUMN_TNAME}, null, null, null);  
        cursor.getCount();  
        while(cursor.moveToNext()) {  
            System.out.println(cursor.getString(cursor.getColumnIndex(Tags.COLUMN_TNAME)));         
        }  
        cursor.close();         
    }  

输出:

enter image description here

如何将结果转换为单个字符串,其中字符用逗号分隔?

2 个答案:

答案 0 :(得分:1)

使用StringBuilder

// ...

final String SEPARATOR = ", ";

StringBuilder builder = new StringBuilder();
String prefix = "";

while(cursor.moveToNext()) {  
    builder.append(prefix);
    prefix = SEPARATOR;
    builder.append(cursor.getString(cursor.getColumnIndex(Tags.COLUMN_TNAME)));    
}  

String output = builder.toString()

// ...

StringBuilder允许您比正常String更快地连接outputString += inputString。这与String对象不可变的事实有关,而StringBuilder不是。{1}}。如果您想了解更多相关信息,请查看在this article

编辑:要将创建的字符串返回给调用方法,必须按以下方式定义方法fetchTags()

public String fetchTags() {

    // your code

    return output;

}

您使用返回类型void定义了它:public void fetchTags() { ... }。这不允许您返回任何值。

完整方法fetchTags() 应如下所示:

public String fetchTags() {
    ContentResolver contentResolver = this.getContentResolver();
    Cursor cursor = contentResolver.query(TagsContentProvider.CONTENT_URI,
        new String[] {
            Tags.COLUMN_TNAME
        }, null, null, null);
    cursor.getCount();

    final String SEPARATOR = ", ";

    StringBuilder builder = new StringBuilder();
    String prefix = "";

    while (cursor.moveToNext()) {
        builder.append(prefix);
        prefix = SEPARATOR;
        builder.append(cursor.getString(cursor.getColumnIndex(Tags.COLUMN_TNAME)));
    }

    String output = builder.toString()

    cursor.close();

    return output;
}

答案 1 :(得分:1)

您可以在打印前将结果累积到StringBuilder

StringBuilder builder = new StringBuilder();

// Special cases: empty cursor and cursor with a single result
if (cursor.moveToNext()) {
    builder.append(cursor.getString(cursor.getColumnIndex(Tags.COLUMN_TNAME)));
}

// Other cases
while(cursor.moveToNext()) {
    builder.append(',')
           .append(cursor.getString(cursor.getColumnIndex(Tags.COLUMN_TNAME)));
}

System.out.println(builder);