How to display all database table data in TextView in android using SQLite

my problem is that the only data that is displayed in the TextView is the last whole row of the table.

so here is my code to get all the data from the 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 to display table data in a 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
source share
2 answers

I would use (for reasons open in other answers)

 tv.append(p.toString()); 

since TextView already saves the text inside.

See TextView.append () .

+1
source

Since you are still creating a new String that is not very good and efficient, and that is the reason that you only have the last line.

So you do this:

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

and this is not very good. If you had milion strings in TABLE , you would have created milion String instances , and that's not very good, would you? Don't forget that String immutable and this kind of work is very expansive, so in such cases you need to use StringBuilder , which has methods that offer excellent performance 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 he is doing the desired work.

+1
source

All Articles