51

データベースクエリの結果を入力するテーブルレイアウトがあります。select allを使用すると、クエリは4行のデータを返します。

このコードを使用して、テーブル行内のTextViewにデータを入力します。

Cursor c = null;
c = dh.getAlternative2();
startManagingCursor(c);
// the desired columns to be bound
String[] columns = new String[] {DataHelper.KEY_ALT};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.name_entry};

SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, 
         R.layout.list_example_entry, c, columns, to);
this.setListAdapter(mAdapter);

KEY_ALTの4つの異なる値を分離して、それらがどこに行くかを選択できるようにしたいと思います。上記の例の1つではなく、4つの異なるTextViewを設定するようにします。

結果のカーソルを反復処理するにはどうすればよいですか?

4

7 に答える 7

111

Cursorデータベースクエリによって返されるオブジェクトは最初のエントリのに配置されるため、反復は次のように簡略化できます。

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

からの参照SQLiteDatabase

于 2012-10-05T08:06:32.797 に答える
82

以下のコードを使用して、カーソルを調べて文字列配列に格納し、4つのテキストビューで設定できます。

String array[] = new String[cursor.getCount()];
i = 0;

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
    array[i] = cursor.getString(0);
    i++;
    cursor.moveToNext();
}
于 2011-02-07T11:17:14.777 に答える
29
for (boolean hasItem = cursor.moveToFirst(); hasItem; hasItem = cursor.moveToNext()) {
    // use cursor to work with current item
}
于 2011-07-22T14:28:21.427 に答える
20

反復は次の方法で実行できます。

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());
    }
}
于 2011-02-07T11:14:10.093 に答える
4

カーソルを反復処理する非常に簡単な方法を見つけました

for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){


    // access the curosr
    DatabaseUtils.dumpCurrentRowToString(cursor);
    final long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));


}
于 2014-01-28T12:47:39.640 に答える
3

私はchiranjibに同意します。私のコードは次のとおりです。

if(cursor != null && cursor.getCount() > 0){
  cursor.moveToFirst();
  do{
    //do logic with cursor.
  }while(cursor.moveToNext());
}
于 2013-04-24T01:49:52.883 に答える
0
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());
    }


}

注:SQLiteQueryBuilder()を使用するには、追加する必要があります

グレードファイルで「com.readystatesoftware.sqliteasset:sqliteassethelper:+」をコンパイルします

于 2017-11-24T07:26:04.270 に答える