java SQLite 查询:获取一行的所有列(android)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17258975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQLite query: get all columns of a row(android)?
提问by Frozen Crayon
Here is the schema:
这是架构:
SQL query is: SELECT * from unjdat where col_1 = "myWord";
SQL查询:从unjdat其中COL_1 = “SELECT * myWord”;
i.e., I want to display all columns for a row whose col_1 is myWord.
即,我想显示 col_1 为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?
我认为问题在于循环。如果我删除for
循环并执行wordsCursor.getString(0)
它的工作。如何循环获取所有列?
Note:
注意:
- col_1 is never null, any of the col_2 to col_11 may be null for some rows.
- All columns and all rows in the table are unique.
- col_1 永远不会为空,对于某些行来说,col_2 到 col_11 中的任何一个都可能为空。
- 表中的所有列和所有行都是唯一的。
回答by MDMalik
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;
EditUser wanted to know how to fill ListView with HashMap
编辑用户想知道如何用 HashMap 填充 ListView
//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 });