java - While 循环停止,但不会继续执行下一条语句

标签 java android mysql

<分区>

我使用 While 循环将 SQL 表的值添加到使用 Cursor 类的 ArrayList 中,但是在添加所有值的那一刻,While 循环停止提供值,但与此同时,它不会'不继续下一个语句。我使用的条件是:如果在 While 循环内 Cursor 有空值,它需要停止(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”,为什么?我该如何解决这个问题?谢谢

最佳答案

这是遍历游标的最佳方式

Cursor cursor = db.rawQuery(...);
try {
        while (cursor.moveToNext()) {
        ...
    }
} finally {
    cursor.close();
}

关于java - While 循环停止,但不会继续执行下一条语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39992426/

相关文章:

php - 来自匹配 mysql 列的多维数组

mysql - 按 asc 和 desc 排序没有给出正确的结果

php - 无法找出 mySQL 语法错误的来源

java - 从一个 Eclipse 插件在另一个插件中访问 jar

java - 如何在 Hadoop-.20 api 中指定 KeyValueTextInputFormat 分隔符?

android - OpenCV imwrite,颜色错误: Which argument for convertTo/cvColor do I use?

android - 位图与 ImageView 与 Drawable

java - 为什么会抛出向上转换检查异常

java - 为什么 Windows 不让 mod_authnz_external 调用的程序使用网络?

java - 如何将字符串值传递给 fragment 上的 AsyncTask