从光标中删除重复数据并在值增加时获取数据

时间:2013-07-31 20:17:49

标签: java android

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

但是,它没有显示出预期的结果。它显示BCNames FERARI TOYOTA AUDI宝马。

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

现在,我的问题是

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

1 个答案:

答案 0 :(得分: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>();
    }
}