没有从数据库sqlite获取记录

时间:2016-06-09 18:20:43

标签: android database sqlite

我不知道我在哪里犯了一个错误,但这里总结了我所做的事情(我在数据库中存储的日期是从日历中选择的,我也存储了日期从日历,所以我以后可以在选定的日期从数据库中获取数据)

mWeekCalendar.setOnDateClickListener(new OnDateClickListener() {
        @Override
        public void onDateClick(DateTime dateTime) {
            // Set text for selected date
            tvDateTime.setText(dateTime.toString(dtf));

            // No record exists under selected date, so we will create a new one
            if (!mDatabase.exists(dateTime.toString(formatter))) {
                Day day = new Day();
                day.setTitle(dateTime.toString(dtfDayInWeek));
                day.setDate(dateTime.toString(formatter));
                mDatabase.createDay(day);
            }

            // Util.showToastMessage(HomeActivity.this, dateTime.toString(formatter);
            // This is working fine and it shows toast message with date

            // Getting a day under selected date
            Day day = mDatabase.getDayByDate(dateTime.toString(formatter));
            Util.showToastMessage(HomeActivity.this, day.getDate());
            // This one shows empty toast message or any other getter i would try here
            // from Day class

        }
    });

如果按选定日期有任何记录,则检查数据库的方法也正常,插入方法也是如此,我可以在数据库的day_date列中看到我从日历dateTime.toString(formatter)传递的值。这就是我从数据库中获取数据的方法:

/**
 * Getting day under date
 */
public Day getDayByDate(String date) {
    SQLiteDatabase db = this.getReadableDatabase();

    String selectQuery = "SELECT * FROM " + TABLE_DAYS + " WHERE "
            + KEY_DAY_DATE + " = " + date;


    Cursor c = db.rawQuery(selectQuery, null);

    Day day = null;

    if (c.getCount() > 0) {
        day.setId(c.getInt((c.getColumnIndex(KEY_ID))));
        day.setTitle((c.getString(c.getColumnIndex(KEY_DAY_NAME))));
        day.setDate((c.getString(c.getColumnIndex(KEY_DAY_DATE))));
        day.setCreated_at(c.getString(c.getColumnIndex(KEY_CREATED_AT)));
    } else {
        day = new Day();
    }

    return day;
}

如果记录在所选日期下存在,此方法将检索记录:

public boolean exists(String date) {
    SQLiteDatabase mDb = this.getReadableDatabase();
    Cursor cursor = mDb.rawQuery("select 1 from " + TABLE_DAYS + " where " + KEY_DAY_DATE + " =?",
            new String[] { date });
    boolean exists = (cursor.getCount() > 0);
    cursor.close();
    return exists;
}

0 个答案:

没有答案