所以我终于让我的listview从我的db查询中显示结果,但由于某种原因它只显示1,最后一个。
public class PastGames extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.pastgames);
DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.getAllFinalscores();
if (c.moveToFirst())
{
do {
String[] listData = new String [] {"Date: " + c.getString(1) + "\n" +
"Strokes: " + c.getString(2) + "\n" + "Holes: " + c.getString(3)};
this.setListAdapter(new ArrayAdapter<String>(this,
R.layout.pastgames, listData));
}
while (c.moveToNext());
}
db.close();
}
}
将对DBAdapter
//***RETRIEVES ALL THE FINALSCORES***//
public Cursor getAllFinalscores()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_DATE,
KEY_FINALSCORE,
KEY_HOLESPLAYED},
null, null, null, null, null);
}
有人能让我知道我做错了什么吗?为什么不显示db中的每一行?
编辑:这是我的xml文件
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:padding="10dp"/>
新(正确方式):
public class PastGames extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.pastgames);
db.open();
Cursor c = db.getAllFinalscores();
String[] listData = new String[c.getCount()];
if (c.moveToFirst())
{
do {
listData[c.getPosition()] = "Date: " + c.getString(1) + "\n" +
"Strokes: " + c.getString(2) + "\n" + "Holes: " + c.getString(3);
}
while (c.moveToNext());
this.setListAdapter(new ArrayAdapter<String>(this,
R.layout.pastgames, listData));
}
db.close()
}
}
答案 0 :(得分:4)
对于数组中的每一行,您都在循环中设置ListAdapter。这就是为什么你只显示最后一个......
String[] listData;
do {
listData[i] = "Date: " + c.getString(1) + "\n" +
"Strokes: " + c.getString(2) + "\n" + "Holes: " + c.getString(3);
}
while (c.moveToNext());
this.setListAdapter(new ArrayAdapter<String>(this,
R.layout.pastgames, listData));
在while循环中填充数组。然后只调用你的this.setListAdapter()一次。这将解决问题
答案 1 :(得分:1)
您正在每次循环执行时初始化列表数据