Detailed Explanation of Android sqlite cursor Traversal Example

  • 2021-12-13 09:35:07
  • OfStack

After the cursor object is queried and obtained, it is traversed with while (corsor. moveToNext ()) {}. When the corsor. moveToNext () method is called, if no object is found, false will be returned


public List<MMImage> getAll() {
        List<MMImage> list = new ArrayList<MMImage>();
        Cursor c = null;
        try {
            c = database.query(TABLE, null, null, null, null, null, null);
            while (c.moveToNext()) {
                MMImage mmImage = getMMImageFromCursor(c);
                list.add(mmImage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return list;
    }

Knowledge point content expansion:

When writing android, it involves the knowledge of sqlite, so I want to make an Demo to learn 1, see the relevant tutorials and help documents, and then start to write their own programs


//1. Get SQLiteDatabase Object of 
SQliteDataBase sqlite = SQliteDatabase.openOrCreateDatabase(new File(Environment.getExternalStorageDirectory() + "\testDB"),null);
//2. Save data into a database 
sqlite.execSQL("create table student(id varchar2(10),name varchar2(20),sex varchar2(2)");
sqlite.execSQL("insert into student values(?,?,?)", new String[] {"2013111111", "Tom", "M" });
//3. From sqlite Read data from 
Cursor cursor = sqlite.rawQuery("select * from student", null);
// Output column name 
for (int i = 0; i < cursor.getColumnCount(); i++) {
   textView.append(cursor.getColumnName(i) + '\t');
}
textView.append("\n");
// Start reading the data in it 
if (cursor.moveToFirst()) {
    do {
        textView.append(cursor.getString(0) 
        + '\t'
    + cursor.getString(1) 
    + '\t' 
    + cursor.getString(2)
    + '\n');
    } while (cursor.moveToNext());

}

It looks very simple, but I forgot to locate cursor when using cursor, because a result set, that is, a 2-dimensional table, is returned after the query. If we call getString directly (int ColumnIndex), an error will be reported, because the cursor cannot determine which row of data you want to return, so we should pay attention to locating the cursor when using Cursor.

The above is Android sqlite cursor traversal example details, more about Android sqlite cursor traversal information please pay attention to other related articles on this site!


Related articles: