Search code examples
calendarandroid-sqliteandroid-cursor

while (cursor.moveToNext()) runs only once in android studio


I want to display different text when I click each date, i checked log and it seems while statement doesn't work after I click once..any idea?

here's my code

 calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
        @Override
        public void onSelectedDayChange(@NonNull CalendarView calendarView, int year, int month, int dayOfMonth) {
            tapDate = year + "/" + (month + 1) + "/" + dayOfMonth;
            selectedDate.setText(tapDate);
            Log.d(TAG, "onSelectedDayChange: tapDate"+ tapDate);

            while (cursor.moveToNext()) {
                item = new Shelf_items();
                item.setBookTitle(cursor.getString(0));
                item.setWriteDate(cursor.getString(1));
                Log.d(TAG, "onSelectedDayChange: while runs");

                if(item.getWriteDate().equals(tapDate)){
                    mShelf.add(item);
                    Log.d(TAG, "onSelectedDayChange: mshelf item"+item);

                    for(Shelf_items i: mShelf){
                        i_result = i.getBookTitle() + " / ";
                    }
                    f_result +=i_result;
                    Log.d(TAG, "onSelectedDayChange: for 문: "+i_result);
                }
                bookName.setText(f_result);
            }
            cursor.close();
            
        }

    });

Solution

  • If you want to loop over the cursor result set again, you need to rewind the cursor back to beginning. Replace the

    while (cursor.moveToNext()) {
        ...
    }
    

    with

    if (cursor.moveToFirst()) {
        do {
            ...
        } while (cursor.moveToNext());
    }
    

    and remove the cursor.close() as you're not yet done with your cursor.