Listview only showing 1 result from query
So I finally got my listview to display result(s) from my db query, but for some reason its only showing 1, the last.
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);
}
Could someone let me know what I am doing wrong? Why is it not d开发者_JAVA技巧isplaying each row in the db?
EDIT: Here is my xml file
<?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"/>
NEW (Correct way):
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()
}
}
For each row in your array your are setting ListAdapter in the loop. This why you only display the last one...
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));
Fill your array in a while loop. And then call your this.setListAdapter() only one time. This will solve the problem
You're reinitilizing ListData on evey loop execution
精彩评论