显示所有Fetched数据SQLite

时间:2016-03-28 15:45:26

标签: java android sqlite

您好我有这个代码从我创建的SQLite本地数据库中检索数据。

下面的代码是一个公共游标,它从数据库中检索我需要的所有数据

public Cursor RetriveAdvertData (DatabasOpperations DBOpp, String Username, String AdvertType){
    SQLiteDatabase SQDB = DBOpp.getReadableDatabase();
    String[] Coloumns = {TableData.TableInfo.USERNAME, TableData.TableInfo.ADVERT_NAME, TableData.TableInfo.ADVERT_EMAIL, TableData.TableInfo.ADVERT_ADDRESS, TableData.TableInfo.ADVERT_NUMBER, TableData.TableInfo.ADVERT_TYPE};
    String Where = TableData.TableInfo.USERNAME + " LIKE ? AND " + TableData.TableInfo.ADVERT_TYPE + " LIKE ?";
    String Argument[] = {Username, AdvertType};
    Cursor Cur = SQDB.query(TableData.TableInfo.TABLE_NAME2, Coloumns, Where, Argument, null, null, null);
    return Cur;
}

然后我在另一个java页面中调用Cursor

Context Contx = this;
public DatabasOpperations DB = new DatabasOpperations(Contx);
public Cursor Cur;
Cur = DB.RetriveAdvertData(DB, DBUsername, "Restaurant");

String AdName = "";
String AdEmail = "";
String AdAddress = "";
String AdNumber = "";
String AdType = "";

if (Cur.moveToFirst()){
            do {
                AdName = Cur.getString(Cur.getColumnIndex("AdvertsName"));
                AdEmail = Cur.getString(Cur.getColumnIndex("AdvertEmail"));
                AdAddress = Cur.getString(Cur.getColumnIndex("AdvertAddress"));
                AdNumber = Cur.getString(Cur.getColumnIndex("AdvertNumber"));
                AdType = Cur.getString(Cur.getColumnIndex("AdvertType"));

                final String[] Adverts = new String[]{
                        AdName, AdEmail, AdAddress, AdNumber, AdType
                };

                ArrayAdapter setListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Adverts);
                LV1.setAdapter(setListAdapter);
            }while (Cur.moveToNext());
        }
        Cur.close();

代码只显示数据库中的一行,如何修改代码以显示数据库中的所有行?

1 个答案:

答案 0 :(得分:0)

尝试将setAdapter放出while循环:

    List<String[]> arr = new ArrayList<>();

    if (Cur.moveToFirst()) {
        do {
            AdName = Cur.getString(Cur.getColumnIndex("AdvertsName"));
            AdEmail = Cur.getString(Cur.getColumnIndex("AdvertEmail"));
            AdAddress = Cur.getString(Cur.getColumnIndex("AdvertAddress"));
            AdNumber = Cur.getString(Cur.getColumnIndex("AdvertNumber"));
            AdType = Cur.getString(Cur.getColumnIndex("AdvertType"));

            final String[] Adverts = new String[]{
                    AdName, AdEmail, AdAddress, AdNumber, AdType
            };

            arr.add(Adverts)
        } while (Cur.moveToNext());
    }
    Cur.close();

    ArrayAdapter setListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arr);
    LV1.setAdapter(setListAdapter);