从游标获取数据并将其存储在字符串数组中

时间:2013-07-31 09:00:09

标签: java android

ID| TOPIC | TITLE | TYPE | NAME |
---------------------------------
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 |

光标保存此表中的数据。现在,我想根据ID| TOPIC | TITLE | TYPE | NAME |获取NAME这里ID这样的数据可以是多个。与ID一样,1 K将为FERARI,TOYOTA,AUDI,BMW,依此类推。我想在customlistview中连续显示此信息。

我的问题是

有没有办法将名称数据存储在String Array中,或者你有什么替代建议吗

2 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,您希望将数据库表中的值存储在数组中吗?为此,您可以创建并行可调整大小的通用列表,如下所示:

ArrayList<int> ids = new ArrayList<int>(); 
ArrayList<String> topics = new ArrayList<String>(); 
ArrayList<String> titles = new ArrayList<String>(); 
ArrayList<String> types = new ArrayList<String>(); 
ArrayList<String> names = new ArrayList<String>(); 

然后您可以像这样添加项目:

ids.add(cursor.getInt(cursor.getColumnIndexOrThrow("_id")));
topics.add(cursor.getString(cursor.getColumnIndexOrThrow("TOPIC")));
titles.add(cursor.getString(cursor.getColumnIndexOrThrow("TITLE")));
types.add(cursor.getString(cursor.getColumnIndexOrThrow("TYPE")));
names.add(cursor.getString(cursor.getColumnIndexOrThrow("NAME")));

P.S。您的数据库看起来有误 - 如果ID是主键(看起来应该是这样),ID列中的值应该是唯一的。

P.S.P.S 另一种选择是使用面向对象的设计 - 创建一个包含id,topic,title,type,name等成员的类。

答案 1 :(得分:0)

public class Product {
    private int id;
    private String topic;
    private String title;
    private String type;
    private String name;

    public Product(Cursor cursor) {
        this.id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
        this.topic = cursor.getString(cursor.getColumnIndexOrThrow("TOPIC"));
        this.title = cursor.getString(cursor.getColumnIndexOrThrow("TITLE")); 
        this.type = cursor.getString(cursor.getColumnIndexOrThrow("TYPE"));
        this.name = cursor.getString(cursor.getColumnIndexOrThrow("NAME"));
    }

    //Getter & Setter here...
}

此产品可能位于以下产品列表中:

ArrayList<Product> products = new ArrayList<Product>();
Product product = new Product(cursor);

products.add(product); // or simpler: products.add(new Product(cursor);

您可以将此列表用于以下目的:

ArrayList<int> ids = new ArrayList<int>(); 
ArrayList<String> topics = new ArrayList<String>(); 
ArrayList<String> titles = new ArrayList<String>(); 
ArrayList<String> types = new ArrayList<String>(); 
ArrayList<String> names = new ArrayList<String>();

for (Product product : products) {
    // for every product in your products list do:  
    ids.add(product.getId);
    topics.add(product.getTopic);
    titles.add(product.getTitle);
    types.add(product.getType);
    names.add(product.getName);
}