问题描述
- SQLite读取全部数据
-
table中一共有11条记录,每个记录有三个内容"name","address","city"。现在要获取这些记录,但是我写的代码只能显示出一条记录,不知道怎么实现显示全部记录?public void readData(View v) { DatabaseClass mydb = new DatabaseClass(this); SQLiteDatabase readdata = mydb.getReadableDatabase(); TextView tv = (TextView)findViewById(R.id.readtext); Cursor c = readdata.rawQuery("select * from mylistdata", null); int[] elementId = {R.id.textView1, R.id.textView2, R.id.textView3}; if(c !=null) { c.moveToFirst(); while(c.isAfterLast() == false) { listData = new ArrayList<GenericListItem>(); String name = c.getString(c.getColumnIndex(DatabaseClass.NAME)); String address = c.getString(c.getColumnIndex(DatabaseClass.ADDRESS)); String city = c.getString(c.getColumnIndex(DatabaseClass.CITY)); listData.add(new GenericListItem(new String[]{name,address,city})); listAdapter = new GenericListAdapter(getApplicationContext(), R.layout.list_layout, listData, elementId); result.setAdapter(listAdapter); c.moveToNext(); } }
解决方案
要把Adapter放到循环前初始化,然后最后再加载(调用setAdapter()),否则每次都对ListView设置了一个新的Adapter,当然只能看到最后一次设置的值了
解决方案二:
在while循环外面初始化listData ArrayList
:
c.moveToFirst();
listData = new ArrayList<GenericListItem>();
while(c.isAfterLast() == false)
{
// add value here to listData
c.moveToNext();
}
// set listData datasource to GenericListAdapter here
listAdapter = new GenericListAdapter(getApplicationContext(),
R.layout.list_layout, listData, elementId);
result.setAdapter(listAdapter);
解决方案三:
listData = new ArrayList<GenericListItem>(); //moved out of loop
while(c.isAfterLast() == false)
{
String name = c.getString(c.getColumnIndex(DatabaseClass.NAME));
String address = c.getString(c.getColumnIndex(DatabaseClass.ADDRESS));
String city = c.getString(c.getColumnIndex(DatabaseClass.CITY));
listData.add(new GenericListItem(new String[]{name,address,city}));
listAdapter = new GenericListAdapter(getApplicationContext(), R.layout.list_layout, listData, elementId);
c.moveToNext();
}
result.setAdapter(listAdapter); // moved out of loop
我认为是循环的问题,你这样写看看
时间: 2024-10-01 21:04:10