我使用While循环使用Cursor类将SQL表的值添加到ArrayList中,但是在添加所有值时,While循环会停止提供值,但同时不会继续接下来的语句。我使用的条件是:如果在While循环内,游标具有null值,则需要停止(c!= null),它会停止但不会继续。我使用Log.i查看在While循环之后是否接收到值,但没有任何值。这是我正在使用的代码:
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
try{
SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("Notes",MODE_PRIVATE, null);
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS notes (name VARCHAR)");
sqLiteDatabase.execSQL("INSERT INTO notes (name) VALUES ('LUIS GA')");
sqLiteDatabase.execSQL("INSERT INTO notes (name) VALUES ('LUIS')");
sqLiteDatabase.execSQL("INSERT INTO notes (name) VALUES ('GA')");
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM notes", null);
int nameIndex = c.getColumnIndex("name");
notes.add("example note");
c.moveToFirst();
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
int i = 0;
Log.i("Bucefalo", Integer.toString(i));
while(c != null){
Log.i("Dato",c.getString(nameIndex));
notes.add(c.getString(nameIndex));
c.moveToNext();
i++;
Log.i("Luis", Integer.toString(i));
};
i = 2;
Log.i("Napoleon", Integer.toString(i));
String Hercules = "Hercules";
Log.i("Hercules",Hercules);
}
catch (Exception e){
e.printStackTrace();
}
我使用Log.i在Logcat中收到的值是“ Bucefalo”和“ Luis”(While循环内的值),但是我没有收到值“ Napoleon”和“ Hercules”,为什么?我该如何解决?谢谢
moveToNext
返回一个布尔值,但同时它继续前进并移动光标。
这样使用
Cursor c = sqLiteDatabase.rawQuery(....);
while (c.moveToNext()) {
}
或者
do {
} while (c.moveToNext());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句