我在从 SQLite
数据库中获取所有数据并将它们显示在 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 个条目:shosho、bosho、gosho,因此我的 ListView 中只有 gosho。知道如何解决这个问题吗?
提前致谢!
最佳答案
更改您的代码,以便在 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);
关于Android ListView Adapter 只显示最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7712612/