4

我的问题是 TextView 中显示的唯一数据是表格的最后一整行。

所以这是我从数据库表中获取全部数据的代码:

public List<Person> getAllPerson()
{
    List<Person> personList = new ArrayList<Person>();

    //select query
    String selectQuery = "SELECT  * FROM " + DATABASE_TABLE;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);


    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
    {
         Person person = new Person();
            person.setId(Integer.parseInt(cursor.getString(0)));
            person.setName(cursor.getString(1));
            person.setHotness(cursor.getString(2));
            person.setAge(Integer.parseInt(cursor.getString(3)));

            // Adding person to list
            personList.add(person);
    }

    return personList;

}

这是我将表格数据显示到 TextView 中的代码:

  public class SQLiteView extends Activity
  {

private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sqlview);
    tv = (TextView) findViewById(R.id.tvDBdisplay);

    DbHelper d = new DbHelper(this);

    List<Person> person = d.getAllPerson();

    for (Person p: person)
    {
        String data =p.getId() + " " + p.getName() + " " + p.getHotness() +      " " + p.getAge();
        tv.setText(data);

    }

   }    
  }
4

2 回答 2

1

Because you still creating new String that is not very good and efficient and this is reason that you have only last row.

So you doing this:

--> get row --> add data to String --> setText
--> get next row --> add data to String --> setText
...
--> get last row --> add data to String --> setText

and this is not very good. In case if you had milion rows in TABLE you would create milion String instances and this is not very good, isn't? Don't forget that String is immutable and this kind of job is very expansive so in similar cases like this you need to use StringBuilder that has methods which offer great work with good performance against String.

StringBuilder builder = new StringBuilder();
for (Person p: person) {
   builder.append(p.getId() + " "
     + p.getName() + " " + p.getHotness() + " " + p.getAge());
}
tv.setText(builder.toString());

Now it's makes desired work.

于 2012-07-04T14:58:06.773 回答
1

我会使用(出于其他答案中公开的原因)

tv.append(p.toString());

因为 TextView 已经在内部保留了文本。

请参阅TextView.append()

于 2012-07-04T16:18:06.813 回答