2013-06-23 22 views
0

這裏是模式:SQLite查詢:獲取一行(android)的所有列?

enter image description here

SQL查詢是: SELECT *從unjdat其中COL_1 = 「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(); 

我認爲問題在於循環。如果我刪除for循環並執行wordsCursor.getString(0)它的作品。 如何循環獲取所有列?

注意

  1. COL_1永遠不能爲null,任何COL_2到col_11可能對某些行是空的。
  2. 表中的所有列和所有行都是唯一的。

回答

11

這是應該的

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; 

編輯用戶想知道如何填寫的ListView與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 }); 
+0

非常感謝你! –

+0

@ArjunU很樂意幫忙 – MDMalik