Android在listview中显示数据库条目

时间:2013-08-23 07:07:09

标签: java android arrays listview

我已搜索过,无法弄清楚为什么我的代码无法正常工作。我想从我的数据库中显示一行,并在列表视图中显示该行的所有记录。代码有效,但它只返回一个listview值,而不是数据库中行的所有记录。这是我更新的代码:

db = openOrCreateDatabase ("Names", MODE_PRIVATE, null); 

    String query = "SELECT * from players";
    Cursor c = db.rawQuery(query, null);
    int count = c.getCount();
    c.moveToFirst();

    ListView layout=(ListView)findViewById(R.id.listView1);  

    for (Integer j = 0; j < count; j++){ 


        String lister = c.getString(c.getColumnIndex("names_of"));

        String[] items = {lister};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
        layout.setAdapter(adapter);
    c.moveToNext();

    }

    db.close();


}

阵列工作不正常,我如何获得超过第一个值?提前谢谢大家
 enter image description here

2 个答案:

答案 0 :(得分:0)

使用这个,你应该将所有值存储在字符串数组中并将适配器行移出循环

for (Integer j = 0; j < count; j++){ 
String[j] items = lister;
}

 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
  layout.setAdapter(adapter);

答案 1 :(得分:0)

试试这段代码。

try to use this:

db = openOrCreateDatabase ("Names", MODE_PRIVATE, null); 

String query = "SELECT * from players";
Cursor c = db.rawQuery(query, null);
int count = 0;
String[] items=new String[c.getCount()]; 

if (c.moveToFirst()) {

  do {
            TextView txt = new TextView(getApplicationContext());
            txt.setText(c.getString(c.getColumnIndex("names_of")));
            txt.setPadding(20, 20, 20, 20);
            txt.setTextSize(20.0f);
            txt.setTextColor(Color.MAGENTA);
            String lister = c.getString(c.getColumnIndex("names_of"));
            items[count] = lister;
            count++;


     } while (c.moveToNext());

   }
  c.close();
 }
  db.close();     
如果items不为空

,则设置适配器之后

  if(items.length>0){
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
      layout.setAdapter(adapter);
  }