Оказавшись в бесконечном цикле - PullRequest
0 голосов
/ 21 марта 2012

Я пытаюсь проверить некоторую информацию в базе данных.Если я запускаю следующий код без цикла, он работает нормально, но проверяет только первую строку, поэтому мне нужно проверить имена и даты каждой строки.

Если я понимаюпри правильном цикле он переместит мой курсор на следующую строку, а затем просто снова запустит код.Кто-нибудь может понять, почему это происходит до тех пор, пока не произойдет сбой моей программы?

while (cursor.moveToNext()) {
String titlefromdb = cursor.getString(3);



if (strTitle.equals(titlefromdb)&& cursor.getString(1).equals(dateselforap)) {


Log.d("insidematch", "date and title matched");

final Dialog matchdiag = new DialogCW2Organisor.this);

matchdiag.setContentView(R.layout.apptmatch);
matchdiag.setTitle("View/Edit Appointment");
matchdiag.setCancelable(true);

TextView matchtxt = (TextView) matchdiag.findViewById(R.id.matchtxt);

matchtxt.setText("Appointment \""+ titlefromdb + "\" already exists, please choose a different event title");

Button btnmatchok = (Button) matchdiag.findViewById(R.id.btnmatch);
btnmatchok.setOnClickListener(new OnClickListener() {

//on click for cancel button
@Override
public void onClick(View v) {
matchdiag.dismiss();}
        });
matchdiag.show();
} else {
addAppt(strTime, strTitle, strDet);
cursor = getAppts();
dialog.dismiss();
}
}

Ответы [ 2 ]

2 голосов
/ 21 марта 2012

Попробуйте перейти к первой записи перед вызовом moveToNext (). Переместите свою функциональность в цикл do / while, чтобы вы могли получить первую запись

if (!cursor.moveToFirst())
    return; //nothing to do since the cursor is empty

do
{
    String titlefromdb = cursor.getString(3);

    if (strTitle.equals(titlefromdb)&& cursor.getString(1).equals(dateselforap)) {
        Log.d("insidematch", "date and title matched");

        final Dialog matchdiag = new DialogCW2Organisor.this);

        matchdiag.setContentView(R.layout.apptmatch);
        matchdiag.setTitle("View/Edit Appointment");
        matchdiag.setCancelable(true);

        TextView matchtxt = (TextView) matchdiag.findViewById(R.id.matchtxt);

        matchtxt.setText("Appointment \""+ titlefromdb + "\" already exists, please choose a different event title");

        Button btnmatchok = (Button) matchdiag.findViewById(R.id.btnmatch);
        btnmatchok.setOnClickListener(new OnClickListener() {

        //on click for cancel button
        @Override
        public void onClick(View v) {
            matchdiag.dismiss();
            }
        });

        matchdiag.show();

    } else {
        addAppt(strTime, strTitle, strDet);
        cursor = getAppts();
        dialog.dismiss();
    }
} while (cursor.moveToNext());
0 голосов
/ 07 апреля 2012

Я также столкнулся с проблемой бесконечного цикла, которая меня действительно озадачила, так как некоторое время цикл! MoveToNext () должен определенно закончить.

Однако, обходной путь должениспользуйте цикл for по длине курсора и обрабатывайте каждый cursor.moveToPosition (i).

for (int i = 0; i <= cursorLen; i++) {
  if (!cursor.moveToPosition(i)) {
    return;
  }
  // process your cursor
}

Мне кажется, что это должно быть ошибкой в ​​реализации Cursor, потому что цикл while над курсором.moveToNext () всегда должен заканчиваться.

...