2 momo1199 Momo1199 于 2013.01.11 16:27 提问

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();
            }



        }

3个回答

cjiiing
cjiiing   2013.01.11 16:34
已采纳

要把Adapter放到循环前初始化,然后最后再加载(调用setAdapter()),否则每次都对ListView设置了一个新的Adapter,当然只能看到最后一次设置的值了

Momo1199
Momo1199 谢谢
接近 5 年之前 回复
redCoral_
redCoral_   2013.01.11 16:51

在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);
Momo1199
Momo1199 你的答案也对,谢谢
接近 5 年之前 回复
O_1001_O
O_1001_O   2013.01.11 16:57
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

我认为是循环的问题,你这样写看看

Csdn user default icon
上传中...
上传图片
插入图片