简体   繁体   中英

how to display the entire database table data into a TextView in android using SQLite

my problem is that the only data that is being display in TextView is the last entire row of the table.

so here is my code for getting the entire data from database table:

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;

}

here is my code for displaying the table data into 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);

    }

   }    
  }

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.

I would use (for the reasons exposed in other answers)

tv.append(p.toString());

because TextView keeps the text internally already.

See TextView.append() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM