Example usage for android.database Cursor getCount

List of usage examples for android.database Cursor getCount

Introduction

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

Prototype

int getCount();

Source Link

Document

Returns the numbers of rows in the cursor.

Usage

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;//from ww  w .  j  a  v a 2 s  . 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:com.sam_chordas.android.stockhawk.ui.MyStocksActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this;
    ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

    setContentView(R.layout.activity_my_stocks);
    // The intent service is for executing immediate pulls from the Yahoo API
    // GCMTaskService can only schedule tasks, they cannot execute immediately
    mServiceIntent = new Intent(this, StockIntentService.class);
    if (savedInstanceState == null) {
        // Run the initialize task service so that some stocks appear upon an empty database
        mServiceIntent.putExtra("tag", "init");
        if (Utils.isNetworkAvailable(mContext)) {
            startService(mServiceIntent);
        } else {//from   w  w w.ja v  a  2s.  co  m
            networkToast();
        }
    }
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    getLoaderManager().initLoader(CURSOR_LOADER_ID, null, this);

    mCursorAdapter = new QuoteCursorAdapter(this, null);
    recyclerView.addOnItemTouchListener(
            new RecyclerViewItemClickListener(this, new RecyclerViewItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View v, int position) {
                    // CursorAdapter returns a cursor at the correct position for getItem(), or null
                    // if it cannot seek to that position.
                    Intent intent = new Intent(getApplicationContext(), LineGraphActivity.class);
                    intent.putExtra(STOCK_ITEM, mCursorAdapter.getItemSymbol(position));
                    startActivity(intent);
                }
            }));
    recyclerView.setAdapter(mCursorAdapter);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.attachToRecyclerView(recyclerView);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Utils.isNetworkAvailable(mContext)) {
                new MaterialDialog.Builder(mContext).title(R.string.symbol_search)
                        .content(R.string.content_test).inputType(InputType.TYPE_CLASS_TEXT)
                        .input(R.string.input_hint, R.string.input_prefill, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                // On FAB click, receive user input. Make sure the stock doesn't already exist
                                // in the DB and proceed accordingly
                                Cursor c = getContentResolver().query(QuoteProvider.Quotes.CONTENT_URI,
                                        new String[] { QuoteColumns.SYMBOL }, QuoteColumns.SYMBOL + "= ?",
                                        new String[] { input.toString() }, null);
                                if (c.getCount() != 0) {
                                    Toast toast = Toast.makeText(MyStocksActivity.this,
                                            "This stock is already saved!", Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, Gravity.CENTER, 0);
                                    toast.show();
                                    return;
                                } else {
                                    // Add the stock to DB
                                    mServiceIntent.putExtra("tag", "add");
                                    mServiceIntent.putExtra("symbol", input.toString());
                                    startService(mServiceIntent);

                                }
                            }
                        }).show();
            } else {
                networkToast();
            }

        }
    });

    ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(mCursorAdapter);
    mItemTouchHelper = new ItemTouchHelper(callback);
    mItemTouchHelper.attachToRecyclerView(recyclerView);

    mTitle = getTitle();
    if (Utils.isNetworkAvailable(mContext)) {
        long period = 30L;
        long flex = 10L;
        String periodicTag = "periodic";

        // create a periodic task to pull stocks once every hour after the app has been opened. This
        // is so Widget data stays up to date.
        PeriodicTask periodicTask = new PeriodicTask.Builder().setService(StockTaskService.class)
                .setPeriod(period).setFlex(flex).setTag(periodicTag)
                .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED).setRequiresCharging(false).build();
        // Schedule task with tag "periodic." This ensure that only the stocks present in the DB
        // are updated.
        GcmNetworkManager.getInstance(this).schedule(periodicTask);
    }

    if (!Utils.isNetworkAvailable(getApplicationContext())) {
        networkToast();
    }
}

From source file:com.ericsender.android_nanodegree.popmovie.com.ericsender.android_nanodegree.popmovie.data.TestProvider.java

public void testGettingMovieAndMaybeFavorite() {
    mContext.getContentResolver().delete(MovieContract.FavoriteEntry.CONTENT_URI, null, null);
    Map<Long, ContentValues> listContentValues = TestUtilities.createSortedMovieValues(getContext(), "popular");

    ContentValues[] arr = (ContentValues[]) listContentValues.values().toArray(new ContentValues[0]);

    mContext.getContentResolver().bulkInsert(MovieContract.MovieEntry.CONTENT_URI, arr);

    ContentValues[] movie_ids = new ContentValues[arr.length];
    for (int i = 0; i < arr.length; i++)
        (movie_ids[i] = new ContentValues()).put(MovieContract.RatingEntry.COLUMN_MOVIE_ID,
                arr[i].getAsLong(MovieContract.MovieEntry.COLUMN_MOVIE_ID));

    mContext.getContentResolver().bulkInsert(MovieContract.FavoriteEntry.CONTENT_URI, movie_ids);

    TestUtilities.verifyFavoriteValuesInDatabase(listContentValues, mContext);

    Long expected = movie_ids[0].getAsLong(MovieContract.MovieEntry.COLUMN_MOVIE_ID);
    Cursor c = mContext.getContentResolver().query(MovieContract.MovieEntry.buildUriUnionFavorite(expected),
            null, null, null, null);/* w  ww . j a v a 2  s. co m*/

    assertTrue(c.moveToFirst());
    assertEquals(2, c.getCount());
    assertEquals(expected.longValue(), c.getLong(0));
    assertTrue(c.moveToNext());
    assertTrue(c.getBlob(1).length > 0);
    c.close();

    mContext.getContentResolver().delete(MovieContract.FavoriteEntry.buildUri(),
            MovieContract.FavoriteEntry.COLUMN_MOVIE_ID + "=?", new String[] { expected.toString() });

    c = mContext.getContentResolver().query(MovieContract.MovieEntry.buildUriUnionFavorite(expected), null,
            null, null, null);

    assertTrue(c.moveToFirst());
    assertEquals(1, c.getCount());
    assertTrue(c.getBlob(1).length > 0);
}

From source file:com.github.wakhub.monodict.activity.FlashcardActivity.java

@UiThread
void onLoadContents(Cursor cursor) {
    Log.d(TAG, "onLoadContents: " + cursor.getCount());

    // how to maintain scroll position of listview when it updates
    // http://stackoverflow.com/questions/10196079
    ListView listView = getListView();
    int lastPosition = listView.getFirstVisiblePosition();
    int lastTopOffset = 0;
    if (listView.getCount() > 0) {
        View view = listView.getChildAt(0);
        if (view != null) {
            lastTopOffset = view.getTop();
        }/*  ww w .  j a v a2s.c o  m*/
    }

    listAdapter = new ListAdapter(this, cursor);
    setListAdapter(listAdapter);

    if (lastPosition > listView.getCount()) {
        listView.setSelection(listView.getCount() - 1);
    } else {
        listView.setSelectionFromTop(lastPosition, lastTopOffset);
    }

    reloadTabs();
    activityHelper.hideProgressDialog();
}

From source file:com.hybris.mobile.app.commerce.fragment.CatalogContentFragmentBase.java

protected void onResponseSearch(String requestId, List<ProductSimple> products,
        SpellingSuggestion spellingSuggestion, Pagination pagination) {
    mInitialCall = false;//www.j a v a2  s.  c o m

    // TODO - offline -  when offline work with the local search
    // We create a cursor based on the results, to use the same adapter as the one used for the product list from a category
    if (products != null) {

        List<DataBaseDataSimple> dataList = new ArrayList<>();

        for (ProductSimple product : products) {
            dataList.add(new DataBaseDataSimple(product.getCode(), product.getData(),
                    CatalogContract.SyncStatus.UPTODATE));
        }

        // Merging old with new cursor - in case of pagination
        Cursor oldCursor = mProductItemsAdapter.getCursor();
        Cursor newCursor = CatalogDatabaseHelper.createCursor(dataList);
        MergeCursor mergeCursor;

        if (oldCursor != null && oldCursor.getCount() > 0) {
            mergeCursor = new MergeCursor(new Cursor[] { oldCursor, newCursor });
        } else {
            mergeCursor = new MergeCursor(new Cursor[] { newCursor });
        }

        mProductItemsAdapter.swapCursor(mergeCursor);
    }

    updateUI(StringUtils.equals(requestId, mSearchRequestId), spellingSuggestion,
            pagination != null ? pagination.getTotalResults() : 0);

    mOnCategorySelectedActivated = true;
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public ChatEntry[] getChats() {
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor chats = db.query(MessageHistoryContract.ChatEntry.TABLE_NAME_ALL_CHATS,
            new String[] { MessageHistoryContract.ChatEntry.COLUMN_NAME_BUDDY_ID,
                    MessageHistoryContract.ChatEntry.COLUMN_NAME_NAME },
            null, null, null, null, MessageHistoryContract.ChatEntry.COLUMN_NAME_NAME);
    int chatCount = chats.getCount();
    ChatEntry[] resultChats = new ChatEntry[chatCount];
    int i = 0;/* w  w w.  j  a  v  a2  s.  c om*/
    chats.moveToFirst();
    if (chats.getCount() > 0)
        do {
            String buddyId = chats.getString(0);
            String name = chats.getString(1);
            MessageArrayContent mac = getLastMessage(buddyId);

            if (mac instanceof TextMessage) {
                TextMessage msg = (TextMessage) mac;

                String lastMessageDate;
                Date msgTime = new Date(msg.time);
                Calendar startOfDay = Calendar.getInstance();
                startOfDay.set(Calendar.HOUR_OF_DAY, 0);
                startOfDay.set(Calendar.MINUTE, 0);
                startOfDay.set(Calendar.SECOND, 0);
                startOfDay.set(Calendar.MILLISECOND, 0);
                long diff = startOfDay.getTimeInMillis() - msgTime.getTime();
                if (diff <= 0)
                    lastMessageDate = String.format(context.getResources().getString(R.string.time), msgTime);
                else if (diff > 1000 * 60 * 60 * 24)
                    lastMessageDate = String.format(context.getResources().getString(R.string.date), msgTime);
                else
                    lastMessageDate = context.getResources().getString(R.string.last_message_yesterday);

                resultChats[i] = new ChatEntry(buddyId, name, MessageHistory.TYPE_TEXT, msg.status,
                        lastMessageDate, ((msg.left) ? name + ": " : "") + msg.message, !msg.left);
            } else if (mac instanceof ImageMessage) {
                ImageMessage msg = (ImageMessage) mac;

                String lastMessageDate;
                Date msgTime = new Date(msg.time);
                Calendar startOfDay = Calendar.getInstance();
                startOfDay.set(Calendar.HOUR_OF_DAY, 0);
                startOfDay.set(Calendar.MINUTE, 0);
                startOfDay.set(Calendar.SECOND, 0);
                startOfDay.set(Calendar.MILLISECOND, 0);
                long diff = startOfDay.getTimeInMillis() - msgTime.getTime();
                if (diff <= 0)
                    lastMessageDate = String.format(context.getResources().getString(R.string.time), msgTime);
                else if (diff > 1000 * 60 * 60 * 24)
                    lastMessageDate = String.format(context.getResources().getString(R.string.date), msgTime);
                else
                    lastMessageDate = context.getResources().getString(R.string.last_message_yesterday);
                msg.description += "".equals(msg.description) ? context.getResources().getString(R.string.image)
                        : "";

                resultChats[i] = new ChatEntry(buddyId, name, MessageHistory.TYPE_IMAGE, msg.status,
                        lastMessageDate, msg.description, !msg.left);
            }
            i++;
        } while (chats.move(1));
    chats.close();
    db.close();
    return resultChats;
}

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Query .../models URI//from w  w w.  j  a v a2s.c  o  m
 */
public void testQueryAllModels() {
    final ContentResolver cr = getContext().getContentResolver();
    // Query all available models
    final Cursor allModels = cr.query(FlashCardsContract.Model.CONTENT_URI, null, null, null, null);
    assertNotNull(allModels);
    try {
        assertTrue("Check that there is at least one result", allModels.getCount() > 0);
        while (allModels.moveToNext()) {
            long modelId = allModels.getLong(allModels.getColumnIndex(FlashCardsContract.Model._ID));
            Uri modelUri = Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI, Long.toString(modelId));
            final Cursor singleModel = cr.query(modelUri, null, null, null, null);
            assertNotNull(singleModel);
            try {
                assertEquals("Check that there is exactly one result", 1, singleModel.getCount());
                assertTrue("Move to beginning of cursor", singleModel.moveToFirst());
                String nameFromModels = allModels
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.NAME));
                String nameFromModel = singleModel
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.NAME));
                assertEquals("Check that model names are the same", nameFromModel, nameFromModels);
                String flds = allModels
                        .getString(allModels.getColumnIndex(FlashCardsContract.Model.FIELD_NAMES));
                assertTrue("Check that valid number of fields", Utils.splitFields(flds).length >= 1);
                Integer numCards = allModels
                        .getInt(allModels.getColumnIndex(FlashCardsContract.Model.NUM_CARDS));
                assertTrue("Check that valid number of cards", numCards >= 1);
            } finally {
                singleModel.close();
            }
        }
    } finally {
        allModels.close();
    }
}

From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java

/**
 * We know that the group exists locally, so we can use the data in the JSON group as gold
 * @param group//w  w  w  .  j a  va 2s  .  co  m
 * @param provider
 * @param authToken
 * @param account
 * @param syncResult
 * @throws JSONException
 * @throws RemoteException
 * @throws OperationApplicationException
 */
private void optimisticallyAddContactsToExistingGroup(JSONObject group, ContentProviderClient provider,
        String authToken, Account account, SyncResult syncResult) throws JSONException, RemoteException {

    if (!group.has(JSONKeys.KEY_MEMBERS)) {
        return;
    }
    String groupCloudId = group.getString(JSONKeys.KEY_ID);
    Cursor groupCursor = provider.query(GMSGroups.CONTENT_URI, new String[] { GMSGroup._ID, GMSGroup.CLOUD_ID },
            GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }, null);
    try {
        if (groupCursor == null || 1 != groupCursor.getCount() || !groupCursor.moveToFirst()) {
            syncResult.databaseError = true;
            return;
        }
        long groupId = groupCursor.getLong(0);
        if (groupId < 0L) {
            syncResult.databaseError = true;
            return;
        }
        // Optimistically add the contacts
        JSONArray membersArray = group.getJSONArray(JSONKeys.KEY_MEMBERS);
        for (int j = 0; j < membersArray.length(); ++j) {
            JSONObject member = membersArray.getJSONObject(j);
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
            // If the first operation asserts it means the contact exists already
            // Operation 0
            ContentProviderOperation op = ContentProviderOperation.newAssertQuery(GMSContacts.CONTENT_URI)
                    .withSelection(GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?",
                            new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) })
                    .withExpectedCount(0).build();
            ops.add(op);
            op = ContentProviderOperation.newInsert(GMSContacts.CONTENT_URI)
                    .withValues(GMSApplication.getMemberValues(member)).withValue(GMSContact.GROUP_ID, groupId)
                    .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).build();
            ops.add(op);
            try {
                @SuppressWarnings("unused")
                ContentProviderResult[] results = provider.applyBatch(ops);
            } catch (OperationApplicationException e) {
                // The contact already exists, so we'll optionally update it, based on its version
                Cursor contactCursor = null;
                try {
                    contactCursor = provider.query(GMSContacts.CONTENT_URI,
                            new String[] { GMSContact._ID, GMSContact.CLOUD_ID, GMSContact.GROUP_ID },
                            GMSContact.CLOUD_ID + "=? AND " + GMSContact.GROUP_ID + "=?",
                            new String[] { member.getString(JSONKeys.KEY_ID), String.valueOf(groupId) }, null);
                    if (contactCursor == null || !contactCursor.moveToFirst()) {
                        syncResult.databaseError = true;
                        return;
                    }
                    // The member already exists, so optinally update it
                    ops = new ArrayList<ContentProviderOperation>();
                    // Operation 0 - we know it exists. If its the right version, we don't need to do the update
                    // So we assert that we'll find zero records with the current version and if that's right, we'll update our
                    // record, including the version with the new record data
                    op = ContentProviderOperation
                            .newAssertQuery(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withSelection(GMSContact.VERSION + "=?",
                                    new String[] { member.getString(JSONKeys.KEY_VERSION) })
                            .withExpectedCount(0).build();
                    ops.add(op);
                    op = ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withValues(GMSApplication.getMemberValues(member))
                            .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1)
                            .build();
                    ops.add(op);
                    provider.applyBatch(ops);
                } catch (OperationApplicationException l) {
                    ops = new ArrayList<ContentProviderOperation>();
                    // Operation 0 - we know it exists and is of the current version, so no update of attributes is needed
                    // We still have to update the status to SYNCED so we don't blow it away later.
                    op = ContentProviderOperation
                            .newUpdate(ContentUris.withAppendedId(GMSContacts.CONTENT_URI,
                                    contactCursor.getLong(0)))
                            .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED).withExpectedCount(1)
                            .build();
                    ops.add(op);
                    try {
                        provider.applyBatch(ops);
                    } catch (OperationApplicationException e1) {
                        syncResult.stats.numSkippedEntries++;
                        e1.printStackTrace();
                    }
                } finally {
                    if (contactCursor != null) {
                        contactCursor.close();
                    }
                }
            }
        }
    } finally {
        if (groupCursor != null) {
            groupCursor.close();
        }
    }
}

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

private void synchronizeOhmlets(final String userId, ContentProviderClient provider)
        throws AuthenticationException, RemoteException, InterruptedException {
    Log.d(TAG, "state of ohmlets sync");

    final CountDownLatch upload;

    // First, sync ohmlet join state. As described by the people field.
    Cursor cursor = null;
    try {/*from   w ww  . j a v a2 s.co  m*/
        cursor = provider.query(OhmageContract.Ohmlets.CONTENT_URI,
                new String[] { OhmageContract.Ohmlets.OHMLET_ID, OhmageContract.Ohmlets.OHMLET_MEMBERS },
                Ohmlets.OHMLET_DIRTY + "=1", null, null);

        upload = new CountDownLatch(cursor.getCount());

        while (cursor.moveToNext()) {
            Member.List members = gson.fromJson(cursor.getString(1), Member.List.class);
            Member m = members.getMember(userId);
            if (m == null) {
                m = members.getMember("me");
                if (m != null) {
                    m.memberId = userId;
                }
            }
            final Member localMember = m;
            ohmageService.getOhmlet(cursor.getString(0)).first(new Func1<Ohmlet, Boolean>() {
                @Override
                public Boolean call(Ohmlet ohmlet) {
                    Member remoteMember = ohmlet.people.getMember(userId);
                    try {
                        if (localMember != null) {
                            if (remoteMember == null || localMember.role != remoteMember.role) {
                                // Check for join verification code to send
                                if (localMember.code != null) {
                                    String code = localMember.code;
                                    localMember.code = null;
                                    ohmageService.updateMemberForOhmlet(ohmlet.ohmletId, localMember, code);
                                } else {
                                    ohmageService.updateMemberForOhmlet(ohmlet.ohmletId, localMember);
                                }
                            }
                        }
                        if (localMember == null && remoteMember != null) {
                            ohmageService.removeUserFromOhmlet(ohmlet.ohmletId, userId);
                        }
                    } catch (AuthenticationException e) {
                        Log.e(TAG, "Error authenticating user", e);
                        Crashlytics.logException(e);
                        mSyncResult.stats.numAuthExceptions++;
                    } catch (RetrofitError e) {
                        Log.e(TAG, "Error synchronizing ohmlet member state", e);
                        Crashlytics.logException(e);
                        mSyncResult.stats.numIoExceptions++;
                    }
                    return true;
                }
            }).finallyDo(new Action0() {
                @Override
                public void call() {
                    upload.countDown();
                }
            }).subscribe();
        }
        cursor.close();

        // Wait for the upload sync operation to finish before downloading the user state
        upload.await();

    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.google.ytd.SubmitActivity.java

private File getFileFromUri(Uri uri) throws IOException {
    Cursor cursor = managedQuery(uri, null, null, null, null);
    if (cursor.getCount() == 0) {
        throw new IOException(String.format("cannot find data from %s", uri.toString()));
    } else {/*  w w  w  .  j av a 2  s .c o m*/
        cursor.moveToFirst();
    }

    String filePath = cursor.getString(cursor.getColumnIndex(Video.VideoColumns.DATA));

    File file = new File(filePath);
    cursor.close();
    return file;
}