JohnD
JohnD

Reputation: 201

Get data from sqlite database

I have an activity and want to get data from my sqlite database. It works, but my activity only retrieves the last row and not the whole column. What can i do to get the whole column?

This is the code in my database:

public String getName() {
String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
c.moveToFirst();
while(!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex(KEY_NAME));
c.moveToNext();
}
c.close();
return name;
}

This is the code in my activities to contact the database:

Database getdata = new Database(this);
getdata.open();
String data = getdata.getName();
getdata.close();

Upvotes: 0

Views: 5709

Answers (3)

user370305
user370305

Reputation: 109237

See, As I said, Without seeing code I m helpless.. And after seeing your code..

You are returning only single String from that function getName() instead it return String[].

Note: this is only pseudo code.. Actual may be different..

public String[] getName() {

        int i=0;
        String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
        Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
        String name[] = new String[c.getCount()];
        c.moveToFirst();
          while(!c.isAfterLast()) {
               name[i] = c.getString(c.getColumnIndex(KEY_NAME));
               c.moveToNext();
               i++;
          }
        c.close();
        return name;
}

And this one,

Database getdata = new Database(this);
getdata.open();
String data[] = getdata.getName();
getdata.close();

Upvotes: 1

Rahmathullah M
Rahmathullah M

Reputation: 2716

Update your code...

public String[] getName() {
    String[] columns = new String[]{ KEY_ROWID, KEY_NAME };
    int i=0;
    Cursor c = db.query(NAME_TABLE, columns, null, null, null, null, null);
    c.moveToFirst();
    String[] names = new String[c.getCount()];
    while(!c.isAfterLast()) {
        String name = c.getString(c.getColumnIndex(KEY_NAME));
        names[i]=name;
        c.moveToNext();
        i++;
    }
    c.close();
    return names;
}

Database getdata = new Database(this);
getdata.open();
String[] data = getdata.getName();
getdata.close();

Upvotes: 1

user1567667
user1567667

Reputation:

use cursor.moveToFirst() method example given below

if (cursor.moveToFirst()) {
             do {
                 list.add(cursor.getString(0));
                 list.add(cursor.getString(1));
                 list.add(cursor.getString(2));
                 list.add(cursor.getString(3));
                 list.add(cursor.getString(4));
                 list.add(cursor.getString(5));
                 list.add(cursor.getString(6));
               } while (cursor.moveToNext());
          }

Upvotes: 2

Related Questions