【发布时间】:2016-06-21 05:32:43
【问题描述】:
您好,我正在制作一个 android 应用程序,我想向数据库中添加一些值,并且我想做 N 次,所以我使用了一个 for 循环,如下所示:
private void addCodeToDataBase() {
for (int i = 1; i <= 100; i++) {
//indexnumber is a TextView
indexNumber.setText("Please enter the TAN code for Index number " + i);
//tanCode is an EditText
if (tanCode.getText().toString() != null) {
//index here is just an int so i can use the i inside the onClick
index = i;
//add is a button
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String codeText = tanCode.getText().toString();
dbHandler.addcode(index, codeText);
}
});
} else {
Toast.makeText(addcode.this, "Please enter your code !!!", Toast.LENGTH_LONG).show();
}
}
}
但我在这里面临的是 for 循环在第一次运行时跳转到 100,我的意思是文本将显示:
请输入索引号 100 的 TAN 代码
它会跳过 99 个数字!!我将如何解决它?
【问题讨论】:
-
发生这种情况是因为您已将
add.setOnClickListener放入您的for循环中,并且当您点击添加按钮时,循环已经执行,从而生成了i = 100的值。 -
不,这是不正确的...... for 循环运行良好......问题是您没有暂停每次迭代的执行,因此它一次完成所有执行......也就是说,for 循环的工作范围是从 1 到 100,但您只能看到第 100 个,因为 for 循环已在 100 处结束..
-
关于如何修复它的任何想法? @拉尔
标签: java android database for-loop logic