Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android sqlite read all rows at once

Is there a way to read all the rows in an sqlite table and display them at once in a textview? This is how I read them and it reads line by line ....

//---retrieves all the titles---
    public Cursor getAllTitles() 
    {
        return db.query(DATABASE_TABLE, new String[] {
                KEY_ROWID, 
                KEY_ISBN,
                KEY_TITLE,
                KEY_PUBLISHER}, 
                null, 
                null, 
                null, 
                null, 
                null);

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.Toast;

public class DatabaseActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DBAdapter db = new DBAdapter(this);

        //---get all titles---
        db.open();
        Cursor c = db.getAllTitles();
        if (c.moveToFirst())
        {
            do {          
                DisplayTitle(c);
            } while (c.moveToNext());
        }
        db.close();
    }    
}

 public void DisplayTitle(Cursor c)
    {
        Toast.makeText(this, 
                "id: " + c.getString(0) + "\n" +
                "ISBN: " + c.getString(1) + "\n" +
                "TITLE: " + c.getString(2) + "\n" +
                "PUBLISHER:  " + c.getString(3),
                Toast.LENGTH_LONG).show();        
    } 
like image 541
moe Avatar asked Dec 28 '22 18:12

moe


1 Answers

First of all, you might want to look into listviews to easily display a list of data like this.

If your goal really is to display all information in one textview (or toast as you're making now), you could try making one large string, with which you create the toast:

    //---get all titles---
    db.open();
    Cursor c = db.getAllTitles();
    String text = "";
    if (c.moveToFirst())
    {
        do {          
            DisplayTitle(c, text);
        } while (c.moveToNext());
    }
    db.close();
    Toast.makeText(this, text, Toast.LENGTH_LONG).show(); 
}

public void DisplayTitle(Cursor c, String text)
{
    text +=
            "id: " + c.getString(0) + "\n" +
            "ISBN: " + c.getString(1) + "\n" +
            "TITLE: " + c.getString(2) + "\n" +
            "PUBLISHER:  " + c.getString(3);        
} 
like image 134
Jolanda Verhoef Avatar answered Jan 04 '23 19:01

Jolanda Verhoef