Java 陷入无限循环
我正试图对数据库中的一些信息进行检查。如果我在没有循环的情况下运行下面的代码,它运行得很好,但只检查第一行,我需要它做的是检查每行的名称和日期 如果我正确理解while循环,它会将光标移动到下一行,然后再次运行代码。有人知道为什么在我的程序崩溃之前这是循环的吗Java 陷入无限循环,java,android,sqlite,infinite-loop,Java,Android,Sqlite,Infinite Loop,我正试图对数据库中的一些信息进行检查。如果我在没有循环的情况下运行下面的代码,它运行得很好,但只检查第一行,我需要它做的是检查每行的名称和日期 如果我正确理解while循环,它会将光标移动到下一行,然后再次运行代码。有人知道为什么在我的程序崩溃之前这是循环的吗 while (cursor.moveToNext()) { String titlefromdb = cursor.getString(3); if (strTitle.equals(titlefromdb)&& c
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();
}
}
在调用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());
我也遇到了无限循环的问题,这也让我很困惑,从一段时间以来!moveToNext循环肯定会完成 但是,解决方法是在光标长度上使用for循环,并处理每个cursor.moveToPositioni
for (int i = 0; i <= cursorLen; i++) {
if (!cursor.moveToPosition(i)) {
return;
}
// process your cursor
}
我觉得这一定是游标实现的一个bug,因为在Cursor.moveToNext上执行while循环应该总是会完成。您能格式化代码吗?如果没有缩进,阅读起来真的很难。你可以尝试用try-catch块来包围代码,看看捕获了什么。