Example usage for android.database Cursor getLong

List of usage examples for android.database Cursor getLong

Introduction

In this page you can find the example usage for android.database Cursor getLong.

Prototype

long getLong(int columnIndex);

Source Link

Document

Returns the value of the requested column as a long.

Usage

From source file:at.bitfire.davdroid.mirakel.resource.LocalAddressBook.java

protected void populateCategories(Contact c) throws RemoteException {
    @Cleanup
    Cursor cursorMemberships = providerClient.query(dataURI(),
            new String[] { GroupMembership.GROUP_ROW_ID, GroupMembership.GROUP_SOURCE_ID },
            GroupMembership.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?",
            new String[] { String.valueOf(c.getLocalID()), GroupMembership.CONTENT_ITEM_TYPE }, null);
    List<String> categories = c.getCategories();
    while (cursorMemberships != null && cursorMemberships.moveToNext()) {
        long rowID = cursorMemberships.getLong(0);
        String sourceID = cursorMemberships.getString(1);

        // either a row ID or a source ID must be available
        String where, whereArg;//from  w ww .  ja v  a2  s  .  c om
        if (sourceID == null) {
            where = Groups._ID + "=?";
            whereArg = String.valueOf(rowID);
        } else {
            where = Groups.SOURCE_ID + "=?";
            whereArg = sourceID;
        }
        where += " AND " + Groups.DELETED + "=0"; // ignore deleted groups
        Log.d(TAG, "Populating group from " + where + " " + whereArg);

        // fetch group
        @Cleanup
        Cursor cursorGroups = providerClient.query(Groups.CONTENT_URI, new String[] { Groups.TITLE }, where,
                new String[] { whereArg }, null);
        if (cursorGroups != null && cursorGroups.moveToNext()) {
            String title = cursorGroups.getString(0);

            if (sourceID == null) { // Group wasn't created by DAVdroid
                // SOURCE_ID IS NULL <=> _ID IS NOT NULL
                Log.d(TAG, "Setting SOURCE_ID of non-DAVdroid group to title: " + title);

                ContentValues v = new ContentValues(1);
                v.put(Groups.SOURCE_ID, title);
                v.put(Groups.GROUP_IS_READ_ONLY, 0);
                v.put(Groups.GROUP_VISIBLE, 1);
                providerClient.update(syncAdapterURI(Groups.CONTENT_URI), v, Groups._ID + "=?",
                        new String[] { String.valueOf(rowID) });

                sourceID = title;
            }

            // add group to CATEGORIES
            if (sourceID != null)
                categories.add(sourceID);
        } else
            Log.d(TAG, "Group not found (maybe deleted)");
    }
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

/**
 * Creates a JSON Object from a Tweet TODO: Move this where it belongs!
 * /* w ww  .java2s .c o  m*/
 * @param c
 * @return
 * @throws JSONException
 */
protected JSONObject getJSON(Cursor c) throws JSONException {
    JSONObject o = new JSONObject();
    if (c.getColumnIndex(Tweets.COL_USER_TID) < 0 || c.getColumnIndex(TwitterUsers.COL_SCREEN_NAME) < 0) {
        Log.i(TAG, "missing user data");
        return null;
    }

    else {

        o.put(Tweets.COL_USER_TID, c.getLong(c.getColumnIndex(Tweets.COL_USER_TID)));
        o.put(TYPE, MESSAGE_TYPE_TWEET);
        o.put(TwitterUsers.COL_SCREEN_NAME, c.getString(c.getColumnIndex(TwitterUsers.COL_SCREEN_NAME)));
        if (c.getColumnIndex(Tweets.COL_CREATED_AT) >= 0)
            o.put(Tweets.COL_CREATED_AT, c.getLong(c.getColumnIndex(Tweets.COL_CREATED_AT)));
        if (c.getColumnIndex(Tweets.COL_CERTIFICATE) >= 0)
            o.put(Tweets.COL_CERTIFICATE, c.getString(c.getColumnIndex(Tweets.COL_CERTIFICATE)));
        if (c.getColumnIndex(Tweets.COL_SIGNATURE) >= 0)
            o.put(Tweets.COL_SIGNATURE, c.getString(c.getColumnIndex(Tweets.COL_SIGNATURE)));

        if (c.getColumnIndex(Tweets.COL_TEXT) >= 0)
            o.put(Tweets.COL_TEXT, c.getString(c.getColumnIndex(Tweets.COL_TEXT)));
        if (c.getColumnIndex(Tweets.COL_REPLY_TO_TWEET_TID) >= 0)
            o.put(Tweets.COL_REPLY_TO_TWEET_TID, c.getLong(c.getColumnIndex(Tweets.COL_REPLY_TO_TWEET_TID)));
        if (c.getColumnIndex(Tweets.COL_LAT) >= 0)
            o.put(Tweets.COL_LAT, c.getDouble(c.getColumnIndex(Tweets.COL_LAT)));
        if (c.getColumnIndex(Tweets.COL_LNG) >= 0)
            o.put(Tweets.COL_LNG, c.getDouble(c.getColumnIndex(Tweets.COL_LNG)));
        if (!c.isNull(c.getColumnIndex(Tweets.COL_MEDIA_URIS))) {
            String photoUri = c.getString(c.getColumnIndex(Tweets.COL_MEDIA_URIS));
            Uri uri = Uri.parse(photoUri);
            o.put(Tweets.COL_MEDIA_URIS, uri.getLastPathSegment());
        }
        if (c.getColumnIndex(Tweets.COL_HTML_PAGES) >= 0)
            o.put(Tweets.COL_HTML_PAGES, c.getString(c.getColumnIndex(Tweets.COL_HTML_PAGES)));
        if (c.getColumnIndex(Tweets.COL_SOURCE) >= 0)
            o.put(Tweets.COL_SOURCE, c.getString(c.getColumnIndex(Tweets.COL_SOURCE)));

        if (c.getColumnIndex(Tweets.COL_TID) >= 0 && !c.isNull(c.getColumnIndex(Tweets.COL_TID)))
            o.put(Tweets.COL_TID, c.getLong(c.getColumnIndex(Tweets.COL_TID)));

        if (c.getColumnIndex(TwitterUsers.COL_PROFILE_IMAGE_URI) >= 0
                && c.getColumnIndex(TweetsContentProvider.COL_USER_ROW_ID) >= 0) {

            String imageUri = c.getString(c.getColumnIndex(TwitterUsers.COL_PROFILE_IMAGE_URI));
            Bitmap profileImage = ImageLoader.getInstance().loadImageSync(imageUri);
            if (profileImage != null) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                profileImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                String profileImageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
                o.put(TwitterUsers.JSON_FIELD_PROFILE_IMAGE, profileImageBase64);
            }
        }

        return o;
    }
}

From source file:edu.cens.loci.provider.LociDbUtils.java

public LociPlace getPlace(long placeId) {
    final SQLiteDatabase db = mDbHelper.getReadableDatabase();

    Cursor cursor = db.query(Tables.PLACES, null, Places._ID + "=" + placeId, null, null, null, null);

    if (cursor.moveToFirst()) {
        LociPlace place = new LociPlace();
        place.placeId = cursor.getLong(cursor.getColumnIndex(Places._ID));
        place.name = cursor.getString(cursor.getColumnIndex(Places.PLACE_NAME));
        place.state = cursor.getInt(cursor.getColumnIndex(Places.PLACE_STATE));
        place.type = cursor.getInt(cursor.getColumnIndex(Places.PLACE_TYPE));
        place.entry = cursor.getInt(cursor.getColumnIndex(Places.ENTRY));
        place.entryTime = cursor.getLong(cursor.getColumnIndex(Places.ENTRY_TIME));
        place.registerTime = cursor.getLong(cursor.getColumnIndex(Places.REGISTER_TIME));

        place.wifis = getWifiFingerprint(placeId);
        place.areas = getGpsCircleArea(placeId);

        if (place.areas == null || place.areas.size() == 0)
            place.areas.add(getPlacePositionEstimate(place.placeId));

        cursor.close();//from w  ww  . j  a va 2  s  .com
        return place;
    }

    cursor.close();
    return null;
}

From source file:com.granita.icloudcalsync.resource.LocalTaskList.java

@Override
public void populate(Resource record) throws LocalStorageException {
    try {//w  w w.j  ava 2s .c o m
        @Cleanup
        final Cursor cursor = providerClient.query(entriesURI(), new String[] { /*  0 */ entryColumnUID(),
                TaskContract.Tasks.TITLE, TaskContract.Tasks.LOCATION, TaskContract.Tasks.DESCRIPTION,
                TaskContract.Tasks.URL, /*  5 */ TaskContract.Tasks.CLASSIFICATION, TaskContract.Tasks.STATUS,
                TaskContract.Tasks.PERCENT_COMPLETE, /*  8 */ TaskContract.Tasks.TZ, TaskContract.Tasks.DTSTART,
                TaskContract.Tasks.IS_ALLDAY, /* 11 */ TaskContract.Tasks.DUE, TaskContract.Tasks.DURATION,
                TaskContract.Tasks.COMPLETED, /* 14 */ TaskContract.Tasks.CREATED,
                TaskContract.Tasks.LAST_MODIFIED, TaskContract.Tasks.PRIORITY }, entryColumnID() + "=?",
                new String[] { String.valueOf(record.getLocalID()) }, null);

        Task task = (Task) record;
        if (cursor != null && cursor.moveToFirst()) {
            task.setUid(cursor.getString(0));

            if (!cursor.isNull(14))
                task.setCreatedAt(new DateTime(cursor.getLong(14)));
            if (!cursor.isNull(15))
                task.setLastModified(new DateTime(cursor.getLong(15)));

            if (!StringUtils.isEmpty(cursor.getString(1)))
                task.setSummary(cursor.getString(1));

            if (!StringUtils.isEmpty(cursor.getString(2)))
                task.setLocation(cursor.getString(2));

            if (!StringUtils.isEmpty(cursor.getString(3)))
                task.setDescription(cursor.getString(3));

            if (!StringUtils.isEmpty(cursor.getString(4)))
                task.setUrl(cursor.getString(4));

            if (!cursor.isNull(16))
                task.setPriority(cursor.getInt(16));

            if (!cursor.isNull(5))
                switch (cursor.getInt(5)) {
                case TaskContract.Tasks.CLASSIFICATION_PUBLIC:
                    task.setClassification(Clazz.PUBLIC);
                    break;
                case TaskContract.Tasks.CLASSIFICATION_CONFIDENTIAL:
                    task.setClassification(Clazz.CONFIDENTIAL);
                    break;
                default:
                    task.setClassification(Clazz.PRIVATE);
                }

            if (!cursor.isNull(6))
                switch (cursor.getInt(6)) {
                case TaskContract.Tasks.STATUS_IN_PROCESS:
                    task.setStatus(Status.VTODO_IN_PROCESS);
                    break;
                case TaskContract.Tasks.STATUS_COMPLETED:
                    task.setStatus(Status.VTODO_COMPLETED);
                    break;
                case TaskContract.Tasks.STATUS_CANCELLED:
                    task.setStatus(Status.VTODO_CANCELLED);
                    break;
                default:
                    task.setStatus(Status.VTODO_NEEDS_ACTION);
                }
            if (!cursor.isNull(7))
                task.setPercentComplete(cursor.getInt(7));

            TimeZone tz = null;
            if (!cursor.isNull(8))
                tz = DateUtils.getTimeZone(cursor.getString(8));

            if (!cursor.isNull(9) && !cursor.isNull(10)) {
                long ts = cursor.getLong(9);
                boolean allDay = cursor.getInt(10) != 0;

                Date dt;
                if (allDay)
                    dt = new Date(ts);
                else {
                    dt = new DateTime(ts);
                    if (tz != null)
                        ((DateTime) dt).setTimeZone(tz);
                }
                task.setDtStart(new DtStart(dt));
            }

            if (!cursor.isNull(11)) {
                DateTime dt = new DateTime(cursor.getLong(11));
                if (tz != null)
                    dt.setTimeZone(tz);
                task.setDue(new Due(dt));
            }

            if (!cursor.isNull(12))
                task.setDuration(new Duration(new Dur(cursor.getString(12))));

            if (!cursor.isNull(13))
                task.setCompletedAt(new Completed(new DateTime(cursor.getLong(13))));
        }

    } catch (RemoteException e) {
        throw new LocalStorageException("Couldn't process locally stored task", e);
    }
}

From source file:com.shafiq.myfeedle.core.MyfeedleCreatePost.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    if (itemId == R.id.menu_post_accounts)
        chooseAccounts();//w  w w.j  av a  2s. co  m
    else if (itemId == R.id.menu_post_photo) {
        boolean supported = false;
        Iterator<Integer> services = mAccountsService.values().iterator();
        while (services.hasNext() && ((supported = sPhotoSupported.contains(services.next())) == false))
            ;
        if (supported) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PHOTO);
        } else
            unsupportedToast(sPhotoSupported);
        //      } else if (itemId == R.id.menu_post_tags) {
        //         if (mAccountsService.size() == 1) {
        //            if (sTaggingSupported.contains(mAccountsService.values().iterator().next()))
        //               selectFriends(mAccountsService.keySet().iterator().next());
        //            else
        //               unsupportedToast(sTaggingSupported);
        //         } else {
        //            // dialog to select an account
        //            Iterator<Long> accountIds = mAccountsService.keySet().iterator();
        //            HashMap<Long, String> accountEntries = new HashMap<Long, String>();
        //            while (accountIds.hasNext()) {
        //               Long accountId = accountIds.next();
        //               Cursor account = this.getContentResolver().query(Accounts.getContentUri(this), new String[]{Accounts._ID, ACCOUNTS_QUERY}, Accounts._ID + "=?", new String[]{Long.toString(accountId)}, null);
        //               if (account.moveToFirst() && sTaggingSupported.contains(mAccountsService.get(accountId)))
        //                  accountEntries.put(account.getLong(0), account.getString(1));
        //            }
        //            int size = accountEntries.size();
        //            if (size != 0) {
        //               final long[] accountIndexes = new long[size];
        //               final String[] accounts = new String[size];
        //               int i = 0;
        //               Iterator<Map.Entry<Long, String>> entries = accountEntries.entrySet().iterator();
        //               while (entries.hasNext()) {
        //                  Map.Entry<Long, String> entry = entries.next();
        //                  accountIndexes[i] = entry.getKey();
        //                  accounts[i++] = entry.getValue();
        //               }
        //               mDialog = (new AlertDialog.Builder(this))
        //                     .setTitle(R.string.accounts)
        //                     .setSingleChoiceItems(accounts, -1, new DialogInterface.OnClickListener() {
        //                        @Override
        //                        public void onClick(DialogInterface dialog, int which) {
        //                           selectFriends(accountIndexes[which]);
        //                           dialog.dismiss();
        //                        }
        //                     })
        //                     .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        //                        @Override
        //                        public void onClick(DialogInterface dialog, int which) {
        //                           dialog.dismiss();
        //                        }
        //                     })
        //                     .create();
        //               mDialog.show();
        //            } else
        //               unsupportedToast(sTaggingSupported);
        //         }
    } else if (itemId == R.id.menu_post_location) {
        LocationManager locationManager = (LocationManager) MyfeedleCreatePost.this
                .getSystemService(Context.LOCATION_SERVICE);
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            mLat = Double.toString(location.getLatitude());
            mLong = Double.toString(location.getLongitude());
            if (mAccountsService.size() == 1) {
                if (sLocationSupported.contains(mAccountsService.values().iterator().next()))
                    setLocation(mAccountsService.keySet().iterator().next());
                else
                    unsupportedToast(sLocationSupported);
            } else {
                // dialog to select an account
                Iterator<Long> accountIds = mAccountsService.keySet().iterator();
                HashMap<Long, String> accountEntries = new HashMap<Long, String>();
                while (accountIds.hasNext()) {
                    Long accountId = accountIds.next();
                    Cursor account = this.getContentResolver().query(Accounts.getContentUri(this),
                            new String[] { Accounts._ID, ACCOUNTS_QUERY }, Accounts._ID + "=?",
                            new String[] { Long.toString(accountId) }, null);
                    if (account.moveToFirst() && sLocationSupported.contains(mAccountsService.get(accountId)))
                        accountEntries.put(account.getLong(account.getColumnIndex(Accounts._ID)),
                                account.getString(account.getColumnIndex(Accounts.USERNAME)));
                }
                int size = accountEntries.size();
                if (size != 0) {
                    final long[] accountIndexes = new long[size];
                    final String[] accounts = new String[size];
                    int i = 0;
                    Iterator<Map.Entry<Long, String>> entries = accountEntries.entrySet().iterator();
                    while (entries.hasNext()) {
                        Map.Entry<Long, String> entry = entries.next();
                        accountIndexes[i] = entry.getKey();
                        accounts[i++] = entry.getValue();
                    }
                    mDialog = (new AlertDialog.Builder(this)).setTitle(R.string.accounts)
                            .setSingleChoiceItems(accounts, -1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    setLocation(accountIndexes[which]);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();
                    mDialog.show();
                } else
                    unsupportedToast(sLocationSupported);
            }
        } else
            (Toast.makeText(this, getString(R.string.location_unavailable), Toast.LENGTH_LONG)).show();
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java

public static <T extends Object> void pushUpdate(String tableName, Class<T> clazz)
        throws ClientProtocolException, IOException, JSONException, Exception {
    SQLiteDatabase db2 = dba.db();/*from   w  w  w.  j a v  a2 s .c o m*/
    Cursor cursorCursor;
    String sql;
    long total;

    sql = "select count(*) from " + tableName + " where updated_on<=0 or remote_key is null or (updated_on > "
            + last_sync_ts;
    if (!tableName.equals(DatabaseHelper.BUDGET_TABLE)) {
        sql = sql + " and updated_on<" + startTimestamp + ")";
    } else {
        sql = sql + ")";
    }

    cursorCursor = db.rawQuery(sql, null);
    cursorCursor.moveToFirst();
    total = cursorCursor.getLong(0);

    sql = "select * from " + tableName + " where updated_on<=0 or remote_key is null or (updated_on > "
            + last_sync_ts;
    if (!tableName.equals(DatabaseHelper.BUDGET_TABLE)) {
        sql = sql + " and updated_on<" + startTimestamp + ")";
    } else {
        sql = sql + ")";
    }

    if (tableName.equals(DatabaseHelper.TRANSACTION_TABLE)) {
        sql += " order by  parent_id asc,_id asc";
    } else if (tableName.equals(DatabaseHelper.BUDGET_TABLE)) {
        sql += " order by  parent_budget_id asc";
    } else if (!tableName.equals("currency_exchange_rate")) {
        sql += " order by  _id asc";
    }

    cursorCursor = db2.rawQuery(sql, null);
    JSONArray resultSet = new JSONArray();

    int i = 0;
    if (cursorCursor.moveToFirst() && isCanceled != true) {
        Log.i("flowzr", "pushing " + tableName);
        do {
            if (i % 10 == 0) {
                //notifyUser(context.getString(R.string.flowzr_sync_sending) + " " + tableName, (int)(Math.round(i*100/total)));
            }
            resultSet.put(cursorToDict(tableName, cursorCursor));
            i++;
            if (i % MAX_PUSH_SIZE == 0) {
                String resp = makeRequest(tableName, resultSet.toString());
                resultSet = new JSONArray();
                if (resp.equals(FLOWZR_MSG_NET_ERROR)) {
                    isCanceled = true;
                }
                if (isCanceled) {
                    return;
                }
            }
        } while (cursorCursor.moveToNext());
    }
    cursorCursor.close();
    if (i % MAX_PUSH_SIZE != 0) {
        String resp = makeRequest(tableName, resultSet.toString());
        if (resp.equals(FLOWZR_MSG_NET_ERROR)) {
            isCanceled = true;
            Log.e("flowzr", resp);
        }
        if (isCanceled) {
            Log.i("flowzr", "sync canceled!");
            return;
        }
    }
}

From source file:org.ohmage.sync.ResponseSyncAdapter.java

@Override
public synchronized void onPerformSync(Account account, Bundle extras, String authority,
        final ContentProviderClient provider, final SyncResult syncResult) {
    Log.d(TAG, "Start onPerformSync()");
    // Check for authtoken
    String token = null;/*w  w  w.  j a  v a  2s. c  o m*/
    try {
        token = am.blockingGetAuthToken(account, AuthUtil.AUTHTOKEN_TYPE, true);
    } catch (OperationCanceledException e) {
        syncResult.stats.numSkippedEntries++;
    } catch (IOException e) {
        syncResult.stats.numIoExceptions++;
    } catch (AuthenticatorException e) {
        syncResult.stats.numAuthExceptions++;
    }

    // If the token wasn't found or there was a problem, we can stop now
    if (token == null || syncResult.stats.numSkippedEntries > 0 || syncResult.stats.numIoExceptions > 0
            || syncResult.stats.numAuthExceptions > 0) {
        Log.d(TAG, "No token found or there was a problem.");
        return;
    }

    // Upload responses
    Observable<Long> toDelete = null;
    Observable<ResponseFiles> filesToDelete = null;

    Cursor cursor = null;

    try {
        cursor = provider.query(Responses.CONTENT_URI,
                new String[] { BaseColumns._ID, Responses.SURVEY_ID, Responses.SURVEY_VERSION,
                        Responses.RESPONSE_DATA, Responses.RESPONSE_METADATA, Responses.RESPONSE_EXTRAS },
                null, null, null);
        AppLogManager.getInstance().logInfo(mContext, "ResponsesSyncStarted",
                cursor.getCount() + " surveys to upload.");
        while (cursor.moveToNext()) {
            final ResponseFiles files = gson.fromJson(cursor.getString(5), ResponseFiles.class);
            try {
                // Make the call to upload responses
                Observable<Response> uploadResponse = null;

                if (Ohmage.USE_DSU_DATAPOINTS_API) {
                    uploadResponse = uploadDatapoint(cursor, files);
                } else {
                    uploadOhmagePoint(cursor, files);
                }

                // Map the data for the upload response to the local id in the db
                final long localResponseId = cursor.getLong(0);
                Observable<Long> responseId = uploadResponse.map(new Func1<Response, Long>() {
                    @Override
                    public Long call(Response response) {
                        return localResponseId;
                    }
                });

                if (toDelete == null) {
                    toDelete = responseId;
                } else {
                    toDelete = Observable.mergeDelayError(responseId, toDelete);
                }

                // Map the data for the upload response to the files in the db
                Observable<ResponseFiles> responseFiles = uploadResponse
                        .map(new Func1<Response, ResponseFiles>() {
                            @Override
                            public ResponseFiles call(Response response) {
                                return files;
                            }
                        });

                if (filesToDelete == null) {
                    filesToDelete = responseFiles;
                } else {
                    filesToDelete = Observable.mergeDelayError(responseFiles, filesToDelete);
                }
            } catch (AuthenticationException e) {
                Crashlytics.logException(e);
                Log.e(TAG, "Auth", e);
                syncResult.stats.numAuthExceptions++;
            } catch (Exception e) {
                Log.e(TAG, "Other uploading error", e);
                Crashlytics.logException(e);
            }
        }
        cursor.close();

    } catch (RemoteException e) {
        Log.e(TAG, "Remote", e);
        Crashlytics.logException(e);
        syncResult.stats.numIoExceptions++;
    } finally {
        if (cursor != null)
            cursor.close();
    }

    if (toDelete != null) {
        Log.d(TAG, "Start deleting responses.");
        toDelete.flatMap(new Func1<Long, Observable<ContentProviderOperation>>() {
            @Override
            public Observable<ContentProviderOperation> call(Long aLong) {
                return Observable.from(ContentProviderOperation.newDelete(
                        appendSyncAdapterParam(ContentUris.withAppendedId(Responses.CONTENT_URI, aLong)))
                        .build());
            }
        }).subscribe(new Subscriber<ContentProviderOperation>() {
            ArrayList<ContentProviderOperation> toDelete = new ArrayList<ContentProviderOperation>();

            @Override
            public void onCompleted() {
                try {
                    getContext().getContentResolver().applyBatch(ResponseContract.CONTENT_AUTHORITY, toDelete);
                } catch (RemoteException e) {
                    syncResult.stats.numIoExceptions++;
                } catch (OperationApplicationException e) {
                    syncResult.stats.numIoExceptions++;
                }
                unsubscribe();
            }

            @Override
            public void onError(Throwable e) {
                // Send error report
                Log.e(TAG, "Upload failed", e);
                Crashlytics.logException(e);
                onCompleted();
            }

            @Override
            public void onNext(ContentProviderOperation args) {
                toDelete.add(args);
            }
        });
    }

    if (filesToDelete != null) {
        filesToDelete.doOnNext(new Action1<ResponseFiles>() {
            @Override
            public void call(ResponseFiles responseFiles) {
                for (String s : responseFiles.getIds()) {
                    responseFiles.getFile(s).delete();
                }
            }
        }).subscribe(new Subscriber<ResponseFiles>() {
            @Override
            public void onCompleted() {
                unsubscribe();
            }

            @Override
            public void onError(Throwable e) {
                Crashlytics.logException(e);
            }

            @Override
            public void onNext(ResponseFiles responseFiles) {

            }
        });
    }
}

From source file:edu.cens.loci.provider.LociDbUtils.java

public ArrayList<LociPlace> getPlaces(String selection) {

    ArrayList<LociPlace> places = new ArrayList<LociPlace>();

    final SQLiteDatabase db = mDbHelper.getReadableDatabase();

    String orderBy = Places.PLACE_NAME + " ASC";

    Cursor cursor = db.query(Tables.PLACES, null, selection, null, null, null, orderBy);

    if (cursor.moveToFirst()) {
        do {//  w ww.jav  a  2s .  c  o  m
            LociPlace place = new LociPlace();
            place.placeId = cursor.getLong(cursor.getColumnIndex(Places._ID));
            place.name = cursor.getString(cursor.getColumnIndex(Places.PLACE_NAME));
            place.state = cursor.getInt(cursor.getColumnIndex(Places.PLACE_STATE));
            place.type = cursor.getInt(cursor.getColumnIndex(Places.PLACE_TYPE));
            place.entry = cursor.getInt(cursor.getColumnIndex(Places.ENTRY));
            place.entryTime = cursor.getLong(cursor.getColumnIndex(Places.ENTRY_TIME));
            place.registerTime = cursor.getLong(cursor.getColumnIndex(Places.REGISTER_TIME));

            place.wifis = getWifiFingerprint(place.placeId);
            place.areas = getGpsCircleArea(place.placeId);

            if (place.state == Places.STATE_DELETED)
                continue;

            places.add(place);
        } while (cursor.moveToNext());
    }
    cursor.close();
    return places;
}