4

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);

    }

   }    
  }
0

2 Answers 2

1

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

tv.append(p.toString());

because TextView keeps the text internally already.

See TextView.append().

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.