SQLite query: get all columns of a row(android)?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-22 00:56:13

问题


Here is the schema:

SQL query is: SELECT * from unjdat where col_1 = "myWord";

i.e., I want to display all columns for a row whose col_1 is myWord.

int i;
String temp;
words = new ArrayList<String>();
Cursor wordsCursor = database.rawQuery("select * from unjdat where col_1 = \"apple\" ", null); //myWord is "apple" here
    if (wordsCursor != null)
        wordsCursor.moveToFirst();
    if (!wordsCursor.isAfterLast()) {
        do {
            for (i = 0; i < 11; i++) {
                temp = wordsCursor.getString(i);
                words.add(temp);
           }
        } while (wordsCursor.moveToNext());
    }
    words.close();

I think the problem lies with the looping. If I remove the for loop and do a wordsCursor.getString(0) it works. How to loop to get all columns?

Note:

  1. col_1 is never null, any of the col_2 to col_11 may be null for some rows.
  2. All columns and all rows in the table are unique.

回答1:


This is how it should be

Cursor cursor = db.rawQuery(selectQuery, null);
    ArrayList<HashMap<String, String>> maplist = new ArrayList<HashMap<String, String>>();
    // looping through all rows and adding to list

    if (cursor.moveToFirst()) {
        do {
            HashMap<String, String> map = new HashMap<String, String>();
            for(int i=0; i<cursor.getColumnCount();i++)
            {
                map.put(cursor.getColumnName(i), cursor.getString(i));
            }

            maplist.add(map);
        } while (cursor.moveToNext());
    }
    db.close();
    // return contact list
    return maplist;

Edit User wanted to know how to fill ListView with HashMap

//listplaceholder is your layout
//"StoreName" is your column name for DB
//"item_title" is your elements from XML

ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.listplaceholder, new String[] { "StoreName",
                "City" }, new int[] { R.id.item_title, R.id.item_subtitle });


来源:https://stackoverflow.com/questions/17258975/sqlite-query-get-all-columns-of-a-rowandroid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!