Pradeep Menon
Pradeep Menon

Reputation: 163

How can I retrieve a particular coloumn from SQLite in android?

I am new bee in ANDROID so am getting problem in retrieving data especially a particular column from SQLite ,can anyone HELP me to know how it is possible.

Upvotes: 3

Views: 8741

Answers (1)

Krishna
Krishna

Reputation: 1474

Retrieving data from SQLite databases in Android is done using Cursors. The Android SQLite query method returns a Cursor object containing the results of the query. To use Cursors android.database.Cursor must be imported.

To get all the column values

Try this

DatabaseHelper mDbHelper = new DatabaseHelper(getApplicationContext());

SQLiteDatabase mDb = mDbHelper.getWritableDatabase();

Cursor cursor = mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
            KEY_DESIGNATION}, null, null, null, null, null);

To get a particular column data

Try this,

Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
              KEY_NAME, KEY_DESIGNATION}, KEY_ROWID + "=" + yourPrimaryKey, null,
              null, null, null, null);
        if (mCursor != null) {
          mCursor.moveToFirst();
        }

After getting the Cursor, you can just iterate for the values like

cur.moveToFirst(); // move your cursor to first row
// Loop through the cursor
        while (cur.isAfterLast() == false) {
             cur.getString(colIndex); // will fetch you the data
            cur.moveToNext();
        }

    cur.close();

Hope this solves your problem.

Upvotes: 6

Related Questions