2014-02-14 58 views
1

我在Android應用程序中遇到問題。我想檢索一列的所有值,但我只獲取其中一個值。我嘗試過所有的東西,但我仍然無法找到解決方案。這裏是我的數據庫中的代碼:光標只返回一個值,不是全部值

public Cursor returnAllColumns() { 
    Cursor cursor = mDb.query(FTS_VIRTUAL_TABLE, 
      new String[] {KEY_ROWID, 
        KEY_NAME, 
      KEY_CUSTOMER, PROTEIN, TOTAL_CARB} 
      , null, null, null, null, null); 
if (cursor != null) { 
     cursor.moveToNext(); 
} 
    return cursor; 
} 

這是我在其他類中的代碼,它顯示了所有值的烤麪包。

mDbHelper = new DBAdapter(DatabaseFiller.this); 
        mDbHelper.open(); 
        Cursor c = mDbHelper.returnAllColumns(); 

        String protein = c.getString(c.getColumnIndexOrThrow("protein")); 

        Toast.makeText(getApplicationContext(), protein, Toast.LENGTH_SHORT).show(); 

我得到的全部是Protein = 0。我應該得到的是0, 0, 0, 0, 0, 0,...。我不知道我在這裏做錯了什麼。在我的ListView中,我明白了。它在那裏完美運作。這是我的ListView代碼:

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
       // Get the cursor, positioned to the corresponding row in the result set 
       cursor = (Cursor) mListView.getItemAtPosition(position); 
       //mListView.setItemChecked(position, true); 
       // Get the state's capital from this row in the database. 
       String name = cursor.getString(cursor.getColumnIndexOrThrow("customer")); 
       String caloriescursor = cursor.getString(cursor.getColumnIndexOrThrow("name")); 
       String totalfat = cursor.getString(cursor.getColumnIndexOrThrow("address")); 
       String satfatcursor = cursor.getString(cursor.getColumnIndexOrThrow("city")); 
       String state = cursor.getString(cursor.getColumnIndexOrThrow("state")); 
       String zipCode = cursor.getString(cursor.getColumnIndexOrThrow("zipCode")); 

然後,返回Toast和一堆值。任何有關這個問題的幫助將不勝感激。

回答

0

getAllColumns(),您的查詢語句是正確的。它確實提取所有列。以下的if聲明只是將其指向第一個結果。然後,您將返回指針指向第一個結果的光標。您應該刪除if聲明,因爲它沒有任何用處。

當試圖展示敬酒,你想是這樣的:

Cursor c = mDbHelper.returnAllColumns(); 
ArrayList<String> protein = new ArrayList<>(); 
while (c.moveToNext()) { 
    protein.add(c.getString(c.getColumnIndexOrThrow("protein"))); 
} 
Toast.makeText(getApplicationContext(), TextUtils.join(", ", protein), Toast.LENGTH_SHORT).show(); 
0

如果遊標返回多行,並且在循環中構建輸出,則需要循環遊標。

繼續呼叫c.moveToNext(),直到它返回false。

+0

嘿,我是Android的初學者。你有一個例子嗎? – Rohodude

0

我有同樣的問題,直到我這樣做:

if (!cursor.moveToFirst()) { 
    Log.d(LOG_TAG, "=== cursor not moveToFirst() ==="); 

    return null; 
} 

Log.d(LOG_TAG, "=== reading cursor of getAll() ==="); 
Log.d(LOG_TAG, String.valueOf(cursor)); 

List<Trip> trips = new ArrayList<>(); 
while (!cursor.isAfterLast()) { 
    trips.add(cursorToTrip(cursor)); 

    cursor.moveToNext(); 
} 

cursor.moveToNext()就永遠不會檢查的第一要素。所以我檢查課程不在最後一個,然後我添加對象並移動到下一個。

就是這樣! :)