SQlite返回0

时间:2017-10-23 09:32:56

标签: android sqlite

首先,我将解释如何从SQLite插入和返回数据。

首先我创建这样的表:

private static final String CREATE_TABLE_STUDENT_LESSON = " create table STUDENTSPECIFICLESSON ( _id TEXT , _viewID INTEGER PRIMARY KEY AUTOINCREMENT , _LESSON_TITLE TEXT , _LESSON_DATE TEXT , _LESSON_PROBLEM TEXT );";

public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE_STUDENT_LESSON);
}

然后我在SQLite中插入这样的表:

public void insertLesson(String _id, String lessonTitle, String lessonDate, String lessonProblem) {
    ContentValues contentValue = new ContentValues();
    contentValue.put(SQLiteHelper._ID, _id);
    contentValue.put(SQLiteHelper.LESSON_TITLE, lessonTitle);
    contentValue.put(SQLiteHelper.LESSON_DATE, lessonDate);
    contentValue.put(SQLiteHelper.LESSON_PROBLEM, lessonProblem);
    this.getWritableDatabase().insert(SQLiteHelper.TABLE_NAME_STUDENTSPECIFICLESSON, null, contentValue);
}

我从Activity中插入它:

sqLiteHelper.insertLesson(id,etLessonTitle.getText().toString(),currentDateandTime,etLessonProbStu.getText().toString());

您会注意到我创建了_viewID INTEGER PRIMARY KEY AUTOINCREMENT我使用它来获取适配器中的特定ViewHolder。

我这样做_viewID

public String getLessonViewHolderID(String _path){
    String id = null;

    Cursor cursor = getReadableDatabase().rawQuery("Select "+SQLiteHelper._viewID+" from "+SQLiteHelper.TABLE_NAME_STUDENTSPECIFICLESSON+" Where "
            +SQLiteHelper.LESSON_TITLE +"='"+_path+"'",null);

    if (cursor != null) {
        cursor.moveToFirst();
    }
    if (cursor == null) {
    } else if (cursor.moveToFirst()) {
        do {
            id = String.valueOf(cursor.getInt(cursor.getColumnIndex(SQLiteHelper._viewID)));

        } while (cursor.moveToNext());
        cursor.close();
    } else {

    }
    return id;
}

这完全有效,并按预期正确返回_viewId

然后我尝试通过这样做从SQLite获取_LESSON_PROBLEM

public String getLessonProblem(String _id){


    String id = null;

    Cursor cursor = getReadableDatabase().rawQuery("Select _LESSON_PROBLEM from "+SQLiteHelper.TABLE_NAME_STUDENTSPECIFICLESSON+" Where "
            +SQLiteHelper._viewID +"='"+_id+"'",null);


    if (cursor != null) {
        cursor.moveToFirst();
    }
    if (cursor == null) {
    } else if (cursor.moveToFirst()) {
        do {
            id = String.valueOf(cursor.getInt(cursor.getColumnIndex("_LESSON_PROBLEM")));

        } while (cursor.moveToNext());
        cursor.close();
    } else {

    }
    return id;

}

我的Adapter致电:

String lessonProblem = helper.getLessonProblem(viewId);

上述String lessonProblem将返回0

我检查了我的数据库并正确插入了所有数据,这是我的数据库的图像:

myDatabase

我无法理解为什么它显然会返回0显然不是,有人可以帮我指出问题所在吗?

2 个答案:

答案 0 :(得分:7)

马虎错误。您应该使用getString()代替getInt()

  

以String形式返回所请求列的值。结果和   当列值为null时,此方法是否抛出异常   或者列类型不是字符串类型是实现定义的。

<强>最后

cursor.getString(cursor.getColumnIndex("_LESSON_PROBLEM"));

答案 1 :(得分:5)

id = String.valueOf(cursor.getInt(cursor.getColumnIndex("_LESSON_PROBLEM")));

您将字符串值作为int获取,然后将其转换为字符串。将其更改为

id = cursor.getString(cursor.getColumnIndex("_LESSON_PROBLEM"));