SQLite查询:获取一行的所有列(Android)? [英] SQLite query: get all columns of a row(android)?

查看:571
本文介绍了SQLite查询:获取一行的所有列(Android)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是架构:

SQL查询为: SELECT * from unjdat,其中col_1 =" myWord ";

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

即,我要显示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();

我认为问题在于循环.如果删除for循环并执行wordsCursor.getString(0),它将起作用. 如何循环获取所有列?

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?

注意:

  1. col_1永远不会为null,对于某些行,col_2至col_11的任何一个都可能为null.
  2. 表中的所有列和所有行都是唯一的.

推荐答案

应该是这样

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;

编辑用户想知道如何用HashMap填充ListView

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 });

这篇关于SQLite查询:获取一行的所有列(Android)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆