如何从(简单)CursorAdapter中的2个表进行查询

时间:2012-04-20 15:03:43

标签: android sqlite

在一张桌子上,我这样做:

public static String[] FROM_Benzinarii_onList = {DBConstants.Denumire_Benzinarie, DBConstants.Adresa, DBConstants.Distance, _ID};

public Cursor getStations_List(){
        db = helper.getReadableDatabase();
        return db.query(DBConstants.TABELA_BENZINARII, FROM_Benzinarii_onList, null, null, null, null, null);

然后构造适配器:

int[] values = {R.id.tv_benzinarie,R.id.tv_adresa,R.id.tv_dist}
Cursor cursor = getStations_List();
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.layout.item_list, cursor,FROM_Benzinarii_onList, values);
     setListAdapter(adapter);

但是现在我需要一个额外的列,价格,从另一个表,我无法获得光标。我已经尝试了下面的代码和许多其他代码。

public static String[] FROM_Benzinarii_onList = {DBConstants.Denumire_Benzinarie, DBConstants.Adresa, DBConstants.Distance, DBConstants.Pret, _ID};

public Cursor getStations_List(){
        db = helper.getReadableDatabase();
        String sql = " select " + DBConstants.TABELA_BENZINARII + "." + DBConstants.Denumire_Benzinarie + "," + DBConstants.TABELA_BENZINARII + "." + DBConstants.Adresa 
                + "," + DBConstants.TABELA_BENZINARII + "." + DBConstants.Distance + "," + DBConstants.TABELA_PRETURI + "." + DBConstants.Pret 
                + " from " + DBConstants.TABELA_PRETURI + "," + DBConstants.TABELA_BENZINARII
                + " where " + DBConstants.TABELA_BENZINARII + "." + DBConstants.ID_Benzinarie + " = " + DBConstants.TABELA_PRETURI + "." + DBConstants.ID_Benz;
        return db.rawQuery(sql, null);
    }

然后以相同的方式构造SimpleAdapter(我不知道它是否正确!?)

int[] values = {R.id.tv_benzinarie,R.id.tv_adresa,R.id.tv_dist,R.id.tv_pret};

Cursor cursor = getStations_List();

SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.layout.item_list, cursor,FROM_Benzinarii_onList, values);
        setListAdapter(adapter);

我明白了:

 Caused by: java.lang.IllegalArgumentException: column '_id' does not exist

我不知道我的新光标是否与FROM_Benzinarii_onList有任何关系但我在这里无法使用db.query 请帮忙!

2 个答案:

答案 0 :(得分:0)

你的结果Cursor中绝对需要一个_id列来在(Simple)CursorAdapter中使用它

答案 1 :(得分:0)

请参阅我的回答Android column _id does not exist problem

在我的回答中尝试使用alias,例如select oid as _id...