从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);
}
}
Run Code Online (Sandbox Code Playgroud)
我的数据库中有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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3136 次 |
| 最近记录: |