2011-10-10 89 views
1

我從SQLite數據庫獲取所有數據並在ListView中顯示它們時遇到了一些問題。我正在使用的代碼僅顯示最後一項。下面是我使用的代碼:Android ListView適配器僅顯示最後一個元素

 ListView lv1 = (ListView) findViewById(R.id.saved_codes_listview); 
     SystemDatabaseHelper systemDbHelper = new SystemDatabaseHelper(this, null, 1); 
     systemDbHelper.initialize(this); 

     String sqlQuery = "SELECT code_id, code_string FROM saved_codes"; 
     Cursor cursor = systemDbHelper.executeSQLQuery(sqlQuery); 
     if(cursor.getCount()==0){ 
      Log.i("No Saved Codes","There is no Saved Codes."); 
     } else if(cursor.getCount()>0){ 
      for(cursor.move(0); cursor.moveToNext(); cursor.isAfterLast()){ 
       String codeString = cursor.getString(cursor.getColumnIndex("code_string")); 
       ArrayList<String> codes = new ArrayList<String>(); 
       codes.add(codeString); 
       Log.i("Code String","Code String : "+codeString); 
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, codes); 
       lv1.setAdapter(adapter); 

      } 
     } 

我在我的數據庫3項爲例:少將,bosho,御所,因此我只有在我的列表視圖御所。任何想法如何解決這個問題?

在此先感謝!

回答

6

更改您的代碼,以便在for循環之前初始化數組列表,並在循環之後設置ArrayAdapter。

ArrayList<String> codes = new ArrayList<String>(); 
for(cursor.move(0); cursor.moveToNext(); cursor.isAfterLast()){ 
       String codeString = cursor.getString(cursor.getColumnIndex("code_string")); 
       codes.add(codeString); 
       Log.i("Code String","Code String : "+codeString);   
} 
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, codes); 
lv1.setAdapter(adapter); 
+0

我可以在此代碼中使用自定義佈局嗎?而不是'android.R.layout.simple_list_item_1'使用'R.layout.savedCodes_layout'? –

+0

通常,您無法將自定義佈局以您編寫的方式添加到ArrayAdapter,除非您的savedCodes_layout只包含一個TextView。 但是,您可以擴展ArrayAdapter類以滿足您的需要並將其設置爲您想要的任何佈局。 – Maggie

0

變化for(cursor.move(0); cursor.moveToNext(); cursor.isAfterLast())

for(cursor.move(0);; cursor.isAfterLast(); cursor.moveToNext())

或使用

while(cursor.isAfterLast()) 
cursor.moveToNext(); 
1

像這樣:

  ArrayList<String> codes = new ArrayList<String>(); 
    for(cursor.move(0); cursor.moveToNext(); cursor.isAfterLast()){ 
      String codeString = cursor.getString(cursor.getColumnIndex("code_string")); 

      codes.add(codeString); 
      Log.i("Code String","Code String : "+codeString); 
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, codes); 
      lv1.setAdapter(adapter); 

     } 

您重新創建在每個循環新ArrayList<String> codes所以最後環路只包含一個元素的列表nt,這是最後一個。

相關問題