以字符串形式检索游标值时出错

Error retrieving cursor value as string

我有一个包含四列的 SQLite 数据库

  1. ID
  2. 姓名
  3. 症状
  4. 医学

我的助手class代码

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

这是我的 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();

其中 t1 是我的文本框,Value1 是我们需要发送给数据库助手以查询数据库的字符串。

当我检查文本框上的输出时,我得到以下输出

    android.database.sqlire.SQLiteCursor@4174986

我应该怎么做才能修复它?

方法 toString() returns 对象 Cursor 的字符串表示。您必须使用 Cursor class.

中的方法 getString(int column)

像这样: med = medicalHelp.getMedicine(Value1).getString(0);

更多信息:https://developer.android.com/reference/android/database/Cursor.html

请改用此方法:

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

然后在你的 activity:

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

即使游标仅包含单个值,它仍然表现为可能具有多列和多行的游标。因此,您必须转到第一行(moveToFirst(),这可能会失败),并从第一列(getString(0))读取值。

但是,对于这种简单的情况,有一个 helper function 可以让您避免使用光标乱搞:

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