2014-01-10 68 views
1

這裏我試圖從SQLite表中獲取所有數據。但每次它只返回最後兩行(我的表只包含兩行)。僅返回SQLite中的最後一個值Select Statement

e.g 
---------------------+ 
| Id| name | mobile |     
|--------------------| 
|1 | abc | 123456 | 
|--------------------| 
|2 | xyz | 789654 | 
+--------------------+ 

我的代碼返回此:

01-11 00:14:59.291: D/Result:(27629): TID 12274, Name: Tablets , Image: [[email protected] 
01-11 00:14:59.291: D/Result:(27629): TID 12274, Name: Tablets , Image: [[email protected] 

在這裏,我貼我的查詢代碼:

public List<ProductCategoryDatabaseRetrieve> getProductCategoryData() { 
    List<ProductCategoryDatabaseRetrieve> productCategoryDatabaseRetrieve = new ArrayList<ProductCategoryDatabaseRetrieve>(); 
    ProductCategoryDatabaseRetrieve prodCatDB = new ProductCategoryDatabaseRetrieve(); 
    SQLiteDatabase sqliteDB = dbHandler.getWritableDatabase(); 
    String[] columns = { DatabaseHandler._TID, 
      DatabaseHandler.TID, 
      DatabaseHandler.PRODUCT_CATEGORY_NAME, 
      DatabaseHandler.PRODUCT_CATEGORY_IMAGE }; 
    Cursor cursor = sqliteDB.query(DatabaseHandler.PRODUCT_CATEGORY_TABLE, 
      columns, null, null, null, null, null); 
    if (cursor.getCount() > 0 && cursor !=null) { 
     while (cursor.moveToNext()) { 
      prodCatDB.set_tid(cursor.getInt(cursor.getColumnIndex(DatabaseHandler._TID))); 
      prodCatDB.setTid(String.valueOf(cursor.getInt(cursor 
        .getColumnIndex(DatabaseHandler.TID)))); 
      prodCatDB.setProductCategoryName(cursor.getString(cursor 
        .getColumnIndex(DatabaseHandler.PRODUCT_CATEGORY_NAME))); 
      prodCatDB.setProductCategoryImage(cursor.getBlob(cursor 
        .getColumnIndex(DatabaseHandler.PRODUCT_CATEGORY_IMAGE))); 
      productCategoryDatabaseRetrieve.add(prodCatDB); 
    } 
    } 
    dbHandler.close(); 
    return productCategoryDatabaseRetrieve; 
} 

感謝很多關於考慮。

回答

3

那是因爲你的實例ProductCategoryDatabaseRetrieve prodCatDB = new ProductCategoryDatabaseRetrieve();while一次循環,然後替換它的屬性值與每次循環迭代。

移動ProductCategoryDatabaseRetrieve prodCatDB = new ProductCategoryDatabaseRetrieve();while循環內像

while (cursor.moveToNext()) { 
     ProductCategoryDatabaseRetrieve prodCatDB = new ProductCategoryDatabaseRetrieve();//Instantiate here with each iteration. 
     prodCatDB.set_tid(cursor.getInt(cursor.getColumnIndex(DatabaseHandler._TID))); 
     prodCatDB.setTid(String.valueOf(cursor.getInt(cursor 
       .getColumnIndex(DatabaseHandler.TID)))); 
     prodCatDB.setProductCategoryName(cursor.getString(cursor 
       .getColumnIndex(DatabaseHandler.PRODUCT_CATEGORY_NAME))); 
     prodCatDB.setProductCategoryImage(cursor.getBlob(cursor 
       .getColumnIndex(DatabaseHandler.PRODUCT_CATEGORY_IMAGE))); 
     productCategoryDatabaseRetrieve.add(prodCatDB); 
} 

而且,在你的if聲明,cursor != null是沒用的。遊標永遠不會爲空,並且即使它是cursor.getCount()也會在達到cursor != null之前拋出空指針異常。刪除cursor != null,你不需要它。

+0

謝謝Yasmani :) – rup35h

+0

沒問題:-)。 – AxiomaticNexus

相關問題