List of usage examples for android.database Cursor moveToNext
boolean moveToNext();
From source file:com.ichi2.anki.stats.OverviewStatsBuilder.java
private List<int[]> _due(Integer start, Integer end, int chunk) { String lim = ""; if (start != null) { lim += String.format(Locale.US, " and due-%d >= %d", mCol.getSched().getToday(), start); }/*from ww w.j av a 2 s . co m*/ if (end != null) { lim += String.format(Locale.US, " and day < %d", end); } List<int[]> d = new ArrayList<>(); Cursor cur = null; try { String query; query = String.format(Locale.US, "select (due-%d)/%d as day,\n" + "sum(case when ivl < 21 then 1 else 0 end), -- yng\n" + "sum(case when ivl >= 21 then 1 else 0 end) -- mtr\n" + "from cards\n" + "where did in %s and queue in (2,3)\n" + "%s\n" + "group by day order by day", mCol.getSched().getToday(), chunk, _limit(), lim); cur = mCol.getDb().getDatabase().rawQuery(query, null); while (cur.moveToNext()) { d.add(new int[] { cur.getInt(0), cur.getInt(1), cur.getInt(2) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } return d; }
From source file:ru.gkpromtech.exhibition.db.Table.java
public List<Pair<Entity[], T>> selectJoined(Join[] joins, String selection, String[] selectionArgs, String orderBy, String groupBy) throws InvalidClassException, IllegalAccessException, InstantiationException { List<Pair<Entity[], T>> result = new ArrayList<>(); Table<? extends Entity>[] tables = new Table<?>[joins.length]; StringBuilder query = new StringBuilder(); for (int i = 0; i < joins.length; ++i) { tables[i] = ((DbHelper) mSqlHelper).getTableFor(joins[i].entity); for (String column : tables[i].mColumns) { query.append(",f").append(i).append(".").append(column); }// w w w . j a v a2s. com } for (String column : mColumns) query.append(",t.").append(column); query.replace(0, 1, "SELECT "); // first comma -> select query.append("\nFROM ").append(mTableName).append(" t"); for (int i = 0; i < joins.length; ++i) { Join join = joins[i]; query.append("\n"); if (join.type != null) query.append(join.type).append(" "); query.append("JOIN ").append(tables[i].mTableName).append(" f").append(i).append(" ON "); if (join.customJoinOn != null) { query.append(join.customJoinOn); } else { query.append("f").append(i).append(".").append(join.entityRow).append(" = t.").append(join.row); } } if (selection != null) query.append("\nWHERE ").append(selection); if (groupBy != null) query.append("\nGROUP BY ").append(groupBy); if (orderBy != null) query.append("\nORDER BY ").append(orderBy); String queryString = query.toString(); if (BuildConfig.DEBUG) Log.d("PP", queryString); SQLiteDatabase db = mSqlHelper.getReadableDatabase(); Cursor cursor = db.rawQuery(queryString, selectionArgs); //noinspection TryFinallyCanBeTryWithResources try { while (cursor.moveToNext()) { int col = 0; Entity[] entities = new Entity[joins.length]; for (int i = 0; i < joins.length; ++i) { Table<? extends Entity> table = tables[i]; entities[i] = joins[i].entity.newInstance(); for (int j = 0; j < table.mFields.length; ++j, ++col) fillFieldValue(table.mType[j], table.mFields[j], entities[i], cursor, col); } T entity = mEntityClass.newInstance(); for (int j = 0; j < mFields.length; ++j, ++col) fillFieldValue(mType[j], mFields[j], entity, cursor, col); result.add(new Pair<>(entities, entity)); } } finally { cursor.close(); db.close(); } return result; }
From source file:ru.gkpromtech.exhibition.db.Table.java
public List<T> select(String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) {/*from w ww.j ava 2 s . c o m*/ List<T> result = new ArrayList<>(); SQLiteDatabase db = mSqlHelper.getReadableDatabase(); Cursor cursor = db.query(mTableName, mColumns, selection, selectionArgs, groupBy, having, orderBy, limit); //noinspection TryFinallyCanBeTryWithResources try { while (cursor.moveToNext()) { T entity = mEntityClass.newInstance(); for (int i = 0; i < mFields.length; ++i) fillFieldValue(mType[i], mFields[i], entity, cursor, i); result.add(entity); } } catch (Exception e) { e.printStackTrace(); } finally { cursor.close(); db.close(); } return result; }
From source file:at.bitfire.davdroid.syncadapter.ContactsSyncManager.java
@Override protected RequestBody prepareUpload(@NonNull LocalResource resource) throws IOException, ContactsStorageException { final Contact contact; if (resource instanceof LocalContact) { LocalContact local = ((LocalContact) resource); contact = local.getContact();//ww w . j a v a2 s. com if (groupMethod == GroupMethod.CATEGORIES) { // add groups as CATEGORIES for (long groupID : local.getGroupMemberships()) { try { @Cleanup Cursor c = provider.query( localAddressBook() .syncAdapterURI(ContentUris.withAppendedId(Groups.CONTENT_URI, groupID)), new String[] { Groups.TITLE }, null, null, null); if (c != null && c.moveToNext()) { String title = c.getString(0); if (!TextUtils.isEmpty(title)) contact.categories.add(title); } } catch (RemoteException e) { throw new ContactsStorageException("Couldn't find group for adding CATEGORIES", e); } } } } else if (resource instanceof LocalGroup) contact = ((LocalGroup) resource).getContact(); else throw new IllegalArgumentException("Argument must be LocalContact or LocalGroup"); App.log.log(Level.FINE, "Preparing upload of VCard " + resource.getFileName(), contact); ByteArrayOutputStream os = new ByteArrayOutputStream(); contact.write(hasVCard4 ? VCardVersion.V4_0 : VCardVersion.V3_0, groupMethod, settings.getVCardRFC6868(), os); return RequestBody.create(hasVCard4 ? DavAddressBook.MIME_VCARD4 : DavAddressBook.MIME_VCARD3_UTF8, os.toByteArray()); }
From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility.java
/** * Gets a list of TransferObserver instances which are observing records * with the given type./* w w w . j a v a 2 s. c o m*/ * * @param type The type of the transfer. * @param states A list of the the transfer states. * @return A list of TransferObserver of transfer records with the given * type and state. */ public List<TransferObserver> getTransfersWithTypeAndStates(TransferType type, TransferState[] states) { final List<TransferObserver> transferObservers = new ArrayList<TransferObserver>(); Cursor c = null; try { c = dbUtil.queryTransfersWithTypeAndStates(type, states); while (c.moveToNext()) { final int partNum = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_PART_NUM)); if (partNum != 0) { // skip parts of a multipart upload continue; } final int id = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_ID)); final TransferObserver to = new TransferObserver(id, dbUtil); to.updateFromDB(c); transferObservers.add(to); } } finally { if (c != null) { c.close(); } } return transferObservers; }
From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.transformationmanager.database.LocalTransformationDBMS.java
public ArrayList<TrafficData> getAllTrafficFromDate(String date, int typeID) { ArrayList<TrafficData> list = new ArrayList<TrafficData>(); String q = "SELECT * FROM " + LocalTransformationDB.TABLE_TRAFFIC_MON // + ";";//from w ww . j a v a2 s. c o m + " where( " + LocalTransformationDB.COLUMN_DATE_TEXT + " like '" + date + "%' AND " + LocalTransformationDB.COLUMN_TYPE + " = " + typeID + ")" + " ORDER BY " + LocalTransformationDB.COLUMN_ID + ";"; Cursor cursor = database.rawQuery(q, null); if (cursor.moveToFirst()) { do { TrafficData trafficData = new TrafficData( cursor.getString(cursor.getColumnIndex(LocalTransformationDB.COLUMN_DATE_TEXT)), cursor.getInt(cursor.getColumnIndex(LocalTransformationDB.COLUMN_TYPE)), cursor.getDouble(cursor.getColumnIndex(LocalTransformationDB.COLUMN_X_AXIS)), cursor.getDouble(cursor.getColumnIndex(LocalTransformationDB.COLUMN_Y_AXIS))); list.add(trafficData); } while (cursor.moveToNext()); } cursor.close(); return list; }
From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferDBUtil.java
/** * Queries uncompleted partUpload tasks of a multipart upload and constructs * a UploadPartRequest for each task. It's used when resuming a multipart * upload//from w ww . j av a2 s. c o m * * @param mainUploadId The mainUploadId of a multipart upload task * @param multipartId The multipartId of a multipart upload task * @return A list of UploadPartRequest */ public List<UploadPartRequest> getNonCompletedPartRequestsFromDB(int mainUploadId, String multipartId) { final ArrayList<UploadPartRequest> list = new ArrayList<UploadPartRequest>(); Cursor c = null; try { c = transferDBBase.query(getPartUri(mainUploadId), null, null, null, null); while (c.moveToNext()) { if (TransferState.PART_COMPLETED.equals( TransferState.getState(c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_STATE))))) { continue; } final UploadPartRequest putPartRequest = new UploadPartRequest() .withId(c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_ID))) .withMainUploadId(c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_MAIN_UPLOAD_ID))) .withBucketName(c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_BUCKET_NAME))) .withKey(c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_KEY))) .withUploadId(multipartId) .withFile(new File(c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_FILE)))) .withFileOffset(c.getLong(c.getColumnIndexOrThrow(TransferTable.COLUMN_FILE_OFFSET))) .withPartNumber(c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_PART_NUM))) .withPartSize(c.getLong(c.getColumnIndexOrThrow(TransferTable.COLUMN_BYTES_TOTAL))) .withLastPart(1 == c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_IS_LAST_PART))); list.add(putPartRequest); } } finally { if (c != null) { c.close(); } } return list; }
From source file:org.noorganization.instalistsynch.controller.synch.impl.ListEntrySynch.java
@Override public void indexLocal(int _groupId, Date _lastIndexTime) { String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000"));//.concat("+0000"); boolean isLocal = false; GroupAuth groupAuth = mGroupAuthDbController.getLocalGroup(); if (groupAuth != null) { isLocal = groupAuth.getGroupId() == _groupId; }/*from w w w . j av a 2s .c om*/ Cursor logCursor = mClientLogDbController.getLogsSince(lastIndexTime, mModelType); if (logCursor.getCount() == 0) { logCursor.close(); return; } try { while (logCursor.moveToNext()) { // fetch the action type int actionId = logCursor.getInt(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION)); eActionType actionType = eActionType.getTypeById(actionId); List<ModelMapping> modelMappingList = mListEntryMapping.get( ModelMapping.COLUMN.GROUP_ID + " = ? AND " + ModelMapping.COLUMN.CLIENT_SIDE_UUID + " LIKE ?", new String[] { String.valueOf(_groupId), logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)) }); ModelMapping modelMapping = modelMappingList.size() == 0 ? null : modelMappingList.get(0); switch (actionType) { case INSERT: // skip insertion because this should be decided by the user if the non local groups should have access to the category // and also skip if a mapping for this case already exists! if (!isLocal || modelMapping != null) { continue; } String clientUuid = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)); Date clientDate = ISO8601Utils.parse( logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)), new ParsePosition(0)); modelMapping = new ModelMapping(null, groupAuth.getGroupId(), null, clientUuid, new Date(Constants.INITIAL_DATE), clientDate, false); mListEntryMapping.insert(modelMapping); break; case UPDATE: if (modelMapping == null) { Log.i(TAG, "indexLocal: the model is null but shouldn't be"); continue; } String timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)); clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0)); modelMapping.setLastClientChange(clientDate); mListEntryMapping.update(modelMapping); break; case DELETE: if (modelMapping == null) { Log.i(TAG, "indexLocal: the model is null but shouldn't be"); continue; } modelMapping.setDeleted(true); timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)); clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0)); modelMapping.setLastClientChange(clientDate); mListEntryMapping.update(modelMapping); break; default: } } } catch (Exception e) { logCursor.close(); } }
From source file:com.example.shutapp.DatabaseHandler.java
/** * Reads the database for all chatrooms. * @return A list of all chatrooms./*ww w . jav a 2 s. com*/ */ public List<Chatroom> getAllChatrooms() { List<Chatroom> chatroomList = new ArrayList<Chatroom>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE_CHATROOMS; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { Chatroom chatroom = new Chatroom(); chatroom.setName(cursor.getString(0)); chatroom.setLatitude(cursor.getDouble(2)); chatroom.setLongitude(cursor.getDouble(StringLiterals.THREE)); chatroom.setRadius(cursor.getFloat(StringLiterals.FOUR)); // Adding chatroom to list chatroomList.add(chatroom); } while (cursor.moveToNext()); } // return contact list return chatroomList; }
From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.transformationmanager.database.LocalTransformationDBMS.java
public JSONArray getAlljsonData() { JSONArray jArray = new JSONArray(); String q = "SELECT * FROM " + LocalTransformationDB.TABLE_JSON_DATA_EXCHANGE + " ORDER BY " + LocalTransformationDB.COLUMN_JSON_ID + ";"; Cursor cursor = database.rawQuery(q, null); if (cursor.moveToFirst()) { do {/*w ww . j a va 2 s . c o m*/ String contents = cursor.getString(cursor.getColumnIndex(LocalTransformationDB.COUMN_JSON_CONTENT)); int id = cursor.getInt(cursor.getColumnIndex(LocalTransformationDB.COLUMN_JSON_ID)); try { JSONObject jObj = new JSONObject(contents); jObj.put(JSONDataExchange.JSON_CONTENT_ID, id); jArray.put(jObj); } catch (JSONException e) { e.printStackTrace(); } } while (cursor.moveToNext()); } cursor.close(); return jArray; }