1

请检查这有什么问题。我正在尝试检索表中的所有记录(包含 3 列的 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();
            }



        }
4

2 回答 2

3

从循环外部初始化listDataArrayList为:While

    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);
于 2013-01-11T06:15:32.467 回答
2

看起来问题在于您每次通过循环都在重新创建列表。试试这个:

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
于 2013-01-11T06:16:26.417 回答