0
1 | AB    | BCD   | ref  | Ferari|
----------------------------------
1 | AB    | BCD   | ref  | TOYOTA|
----------------------------------
1 | AB    | BCD   | ref| AUDI |
----------------------------------
1 | AB    | BCD    | ref| BMW  |
---------------------------------
2 | BC    | ABC   | ref  | NISSAN|
----------------------------------
2 | BC    | ABC   | ref  | SUZKI|
----------------------------------
2 | BC    | ABC   | ref| TATA |

光标保存像这张表一样的数据。现在,我想得到像

getTopic = AB
getTitle= BCD
getType = ref
Names   = FERARI TOYOTA AUDI BMW

我试过这个

   do{
       int current = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
       String Title = cursor.getString(cursor.getColumnIndexOrThrow("TITLE"));
       if(!StoreTitle.equalsIgnoreCase(Title) && lastId != current){

           getTopic = cursor.getString(cursor.getColumnIndexOrThrow("TOPIC"));
           getTitle = cursor.getString(cursor.getColumnIndexOrThrow("TITLE"));
           getType = cursor.getString(cursor.getColumnIndexOrThrow("TYPE"));
           getName = cursor.getString(cursor.getColumnIndexOrThrow("NAME"));

       }else{
              getName = getName +" "+ cursor.getString(cursor.getColumnIndexOrThrow("NAME"));
           }

       lastId = current;
       StoreTitle = Title;
 }while(cursor.moveToNext());

但是,它没有显示预期的结果。它正在显示BCNamesFERARI TOYOTA AUDI BMW 的专栏。

因为我也在检查lastitem!= currentitem这个,它也没有显示最后的作者姓名。

现在,我的问题是

1)我应该怎么做才能得到预期的结果?2)由于我也在检查lastitem!= currentitem这一点,它也没有显示最后的作者姓名。但是,我如何存储该名称。

4

1 回答 1

0

这应该有效(未经测试)

SparseArray<Data> dataArray = new SparseArray<Data>();
    cursor.moveToFirst();
    do {
        int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
        String title = cursor.getString(cursor.getColumnIndex("TITLE"));
        String topic = cursor.getString(cursor.getColumnIndex("TOPIC"));
        String type = cursor.getString(cursor.getColumnIndex("TYPE"));
        String name = cursor.getString(cursor.getColumnIndex("NAME"));
        Data d = dataArray.get(id);
        if (d == null) {
            d = new Data(id, title, topic, type);
            d.names.add(name);
            dataArray.put(id, d);
        } else {
            d.names.add(name);
        }
    } while (cursor.moveToNext());


// now you can get names like this
    for (int i = 0; i < dataArray.size(); i++) {
        Data d = dataArray.get(i);
        String names = TextUtils.join(" ", d.names); 
    }

在哪里Data

private class Data {
    int id;
    String title, topic, type;
    List<String> names;

    public Data(int id, String title, String topic, String type) {
        this.id = id;
        this.title = title;
        this.topic = topic;
        this.type = type;
        names = new ArrayList<String>();
    }
}
于 2013-07-31T20:54:12.343 回答