Android Application Development (AND-401) — Question 98
Consider the following code snippet to query SQLite database:
String[] result_columns = new String[] {KEY_ID, COL1, COL2};
Cursor allRows = myDatabase.query(true, DATABASE_TABLE, result_columns, null, null, null, null, null, null);
Which of the following prints out the values of COL1 column correctly if the result is not empty?
Answer options
- A. if (allRows.moveToFirst()) { do { System.out.println(allRows.getString(1)); } while (allRows.moveToNext()); }
- B. do { System.out.println(allRows.getString(0)); } while (allRows.moveToNext());
- C. if (allRows.moveToFirst()) { do { System.out.println(allRows.getString(0)); } while (allRows.moveToNext()); }
- D. if (allRows!= null) { do { System.out.println(allRows.getString(1)); }
Correct answer: A
Explanation
Option A is correct as it checks if there are rows in the cursor and uses the correct index (1) to access COL1. Option B incorrectly uses index 0, which corresponds to KEY_ID. Option C also incorrectly uses index 0 instead of 1, while Option D lacks the necessary closing brace and does not ensure the cursor is moved to the first row before accessing data.