android sqlite cursor:获取多个类似的数据

时间:2011-12-08 13:08:33

标签: android database sqlite cursor

我想检索用户的分数。用户可以有多个分数。但如果用户有多个分数,则只显示最后一个分数,而不是所有分数。

这些是我的代码

ScoreDetailActivity.java

public class ScoreDetailActivity extends Activity {

    protected TextView userName;
    protected TextView score;
    protected int user_Id;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.scoredetail);

    user_Id = getIntent().getIntExtra("USER_ID", 0);
    SQLiteDatabase db = (new DatabaseUsername(this)).getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT alm._id, alm.nama, alm.jekel, sc._id, sc.score, sc.userId FROM almag alm LEFT OUTER JOIN score sc ON alm._id = sc.userId WHERE alm._id = ?",
                            new String[]{""+user_Id});

            if (cursor.moveToFirst()){
                do {
                        userName = (TextView) findViewById(R.id.userName);
                        userName.setText(cursor.getString(cursor.getColumnIndex("nama"))); 
                            score = (TextView) findViewById(R.id.score);
                            score.setText(cursor.getString(cursor.getColumnIndex("score")));
                   } while (cursor.moveToNext());
                }

}}

scoredetail.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
    <TextView
            android:id="@+id/userName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
            android:id="@+id/score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

我希望有人可以帮助我。谢谢

2 个答案:

答案 0 :(得分:1)

每次循环时都会覆盖数据和对象 试试这个

userName = (TextView) findViewById(R.id.userName);
userName.setText(cursor.getString(cursor.getColumnIndex("nama"))); 
score = (TextView) findViewById(R.id.score);

StringBuffer data = new StringBuffer();
do {
   data.append(cursor.getString(cursor.getColumnIndex("score"))+"\n");
}while(cursor.moveToNext());
score.setText(data.toString());

答案 1 :(得分:0)

通过游标的每次迭代,您将覆盖文本视图中的值。您需要将游标结果放入一个数组中,然后将它们连接成一个长字符串,或者使用一个可以处理多个值的小部件,如:

<EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textMultiLine">
</EditText>