Iterate through rows from Sqlite-query

后端 未结 7 1164
梦如初夏
梦如初夏 2020-12-02 17:57

I have a table layout that I want to populate with the result from a database query. I use a select all and the query returns four rows of data.

I use this code to

相关标签:
7条回答
  • 2020-12-02 18:38

    Found a very simple way to iterate over a cursor

    for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
    
    
        // access the curosr
        DatabaseUtils.dumpCurrentRowToString(cursor);
        final long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
    
    
    }
    
    0 讨论(0)
  • 2020-12-02 18:42

    Iteration can be done in the following manner:

    Cursor cur = sampleDB.rawQuery("SELECT * FROM " + Constants.TABLE_NAME, null);
    ArrayList temp = new ArrayList();
    if (cur != null) {
        if (cur.moveToFirst()) {
            do {
                temp.add(cur.getString(cur.getColumnIndex("Title"))); // "Title" is the field name(column) of the Table                 
            } while (cur.moveToNext());
        }
    }
    
    0 讨论(0)
  • 2020-12-02 18:47
    public void SQLfunction() {
        SQLiteDatabase db = getReadableDatabase();
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    
        String[] sqlSelect = {"column1","column2" ...};
        String sqlTable = "TableName";
        String selection = "column1= ?"; //optional
        String[] selectionArgs = {Value}; //optional
    
        qb.setTables(sqlTable);
        final Cursor c = qb.query(db, sqlSelect, selection, selectionArgs, null, null, null);
    
       if(c !=null && c.moveToFirst()){
            do {
               //do operations
               // example : abcField.setText(c.getString(c.getColumnIndex("ColumnName")))
    
              }
            while (c.moveToNext());
        }
    
    
    }
    

    NOTE: to use SQLiteQueryBuilder() you need to add

    compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+' in your grade file

    0 讨论(0)
  • 2020-12-02 18:53

    Cursor objects returned by database queries are positioned before the first entry, therefore iteration can be simplified to:

    while (cursor.moveToNext()) {
        // Extract data.
    }
    

    Reference from SQLiteDatabase.

    0 讨论(0)
  • 2020-12-02 18:53
    for (boolean hasItem = cursor.moveToFirst(); hasItem; hasItem = cursor.moveToNext()) {
        // use cursor to work with current item
    }
    
    0 讨论(0)
  • 2020-12-02 18:56

    I agree to chiranjib, my code is as follow:

    if(cursor != null && cursor.getCount() > 0){
      cursor.moveToFirst();
      do{
        //do logic with cursor.
      }while(cursor.moveToNext());
    }
    
    0 讨论(0)
提交回复
热议问题