Search code examples
androidsqliteandroid-datepicker

Problem getting data from DB using DatePicker date


Hey I got a problem here.

I'm trying to retrieve the date from the Database based on Date passed to the method, and it returns the value.

The problem is that, when I try to pass the variable that receives the date, the method that select the data from the DB, returns nothing. (and I print the date variable on the LogCat and it's ok, the date value is correct), but if I pass a String value like this ("1/01/1111") it returns correctly.

here is the method on the activity that get the value and set the text.

public void setBasicContent() {

    date = (mMonth + 1) + "/" + mDay + "/" + mYear + " ";
    hpdData = this.hpd.selectDuration(date);
    mDateDisplay.setText(hpdData);

}

And here is the selectDuration() method that select the data from the DB based on the date parameter.

Ah, when I pass the variable date in the activity, the code doesn't reach the if(cursor.moveToFirst()) scope. But I don't know why, because the variable value is completely correctly exactly like a normal string.

public String selectDuration(String date) {

    String duration = "";
    Integer value = 0;
    String returnment = "";
    Log.i(TAG, "date to select: " + date);
    Cursor cursor = this.db.query(TABLE_NAME, new String[] { "duration" },
            "date = ?", new String[] { date }, null, null, null);

    if (cursor.moveToFirst()) {
        do {
            Log.i("SELECTDURATION", "inside cursor.moveToFirst()");
            duration = cursor.getString(0);
            value += Integer.parseInt(duration);

        } while (cursor.moveToNext());
        returnment = Integer.toString(value);
    }

    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    Log.i(TAG, "valor do returnment: " + returnment);
    return returnment;
}

Solution

  • I found the error. It is on the setBasicContent() method.

    Here is the old method:

    public void setBasicContent() {
    
    date = (mMonth + 1) + "/" + mDay + "/" + mYear + " ";
    hpdData = this.hpd.selectDuration(date);
    mDateDisplay.setText(hpdData);
    

    }

    and here is the new method modified:

    public void setBasicContent() {
    
    date = (mMonth + 1) + "/" + mDay + "/" + mYear;
    hpdData = this.hpd.selectDuration(date);
    mDateDisplay.setText(hpdData);
    

    }

    The problem is on this line:

     date = (mMonth + 1) + "/" + mDay + "/" + mYear + " ";
    

    If you see, it concatenates an empty character to the date, so in the String will pass the date string with an empty character, which for a String makes the difference. So it must be like this:

    date = (mMonth + 1) + "/" + mDay + "/" + mYear;