Crazy Programmer
Crazy Programmer

Reputation: 196

Error retrieving cursor value as string

I have an SQLite-Database with four columns

  1. ID
  2. Name
  3. symptoms
  4. Medicine

My Helper class code

        public Cursor getMedicine(String symptom1)
        {

            SQLiteDatabase db=helper.getReadableDatabase();
            Cursor c =  db.rawQuery("SELECT medicine FROM diseases WHERE symptoms = ?;",new String[] {symptom1});
            c.moveToFirst();
            return c;
        }

And here is code of my activity class :

    String med = "";

    Disp_med_DBHelper medicalHelp = new Disp_med_DBHelper(this);
    medicalHelp.open();
    medicalHelp.getMedicine(Value1);
    med = medicalHelp.getMedicine(Value1).toString();

    t1.setText(med);
    medicalHelp.close();

Where t1 is my textbox, and Value1 is the string that we need to send to database helper to query the database.

When I check output on my textbox, I get the following output

    android.database.sqlire.SQLiteCursor@4174986

What should I do to get it fixed?

Upvotes: 0

Views: 291

Answers (3)

CL.
CL.

Reputation: 180030

Even when the cursor contains only a single value, it still behaves as a cursor that might have multiple columns and multiple rows. So you have to go to the first row (with moveToFirst(), which might fail), and read the value from the first column (with getString(0)).

However, for this simple situation, there is a helper function that allows you to avoid having to muck around with a cursor:

    public Cursor getMedicine(String symptom1) {
        SQLiteDatabase db = helper.getReadableDatabase();
        return DatabaseUtils.stringForQuery(db,
                    "SELECT medicine FROM diseases WHERE symptoms = ?;",
                    new String[]{ symptom1 });
    }

Upvotes: 0

Ali Sherafat
Ali Sherafat

Reputation: 3855

use this method instead:

  public String getMedicine(String symptom1) {
    SQLiteDatabase db = helper.getWritableDatabase();
    Cursor c = db.rawQuery("SELECT medicine FROM diseases WHERE symptoms = ?;", new String[]{symptom1});
    if (c.moveToFirst()) {
        return c.getString(c.getColumnIndex("medicine"));
    }
    return null;
}

and then in your activity:

med = medicalHelp.getMedicine(Value1)
if(med!=null){
   t1.setText(med);
}

Upvotes: 1

Sergey Chechenev
Sergey Chechenev

Reputation: 79

Method toString() returns string representation of object Cursor. You have to use method getString(int column) from Cursor class.

Something like this: med = medicalHelp.getMedicine(Value1).getString(0);

More info: https://developer.android.com/reference/android/database/Cursor.html

Upvotes: 1

Related Questions