2011-10-10 52 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,这是最后一个。

相关问题