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:com.oxgcp.photoList.PhotolistModule.java

@Kroll.method
public KrollDict getPhotos(Integer date, Integer limit) {
    Uri externalPhotosUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    // Uri internalPhotosUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
    Activity activity = this.getActivity();
    Gson gson = new Gson();

    String orderBy;// w w  w.ja  v a 2 s.co m
    if (date == null)
        date = 0;
    if (limit == null) {
        orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC";
    } else {
        orderBy = MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC LIMIT " + limit;
    }

    String[] where = { date.toString() };

    HashMap<String, String> obj = new HashMap<String, String>();
    // HashMap<String, KrollDict> photos = new HashMap<String, KrollDict>();
    // KrollDict dict;

    // String[] projection = new String[]{
    //    MediaStore.Images.Media._ID,
    //    MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
    //    MediaStore.Images.Media.DATE_TAKEN
    // };

    Cursor externalList = activity.managedQuery(externalPhotosUri, null,
            MediaStore.Images.ImageColumns.DATE_TAKEN + " > ? ", where, orderBy);
    // null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC WHERE " + MediaStore.Images.ImageColumns._ID + " > " + id + " LIMIT " + limit);
    // Cursor internalList = activity.managedQuery(internalPhotosUri, null, null, null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");

    // ArrayList<String> arrayList = new ArrayList<String>();
    KrollDict arrayList = new KrollDict(externalList.getCount());

    externalList.moveToFirst();
    // internalList.moveToFirst();

    Log.d("TiAPI", "externalList's count: " + externalList.getCount());
    if (externalList.getCount() > 0) {
        for (Integer i = 0; !externalList.isAfterLast(); i++) {

            obj.put("path", externalList.getString(externalList.getColumnIndex(MediaStore.MediaColumns.DATA)));
            obj.put("date", externalList
                    .getString(externalList.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN)));

            // dict = new KrollDict(obj);

            arrayList.put(i.toString(), new KrollDict(obj)); //add the item
            externalList.moveToNext();
        }
    }

    // Log.d("TiAPI", "internalList's count: " + internalList.getCount());
    // if (internalList.getCount() > 0) {
    //    while(!internalList.isAfterLast()) {
    //          arrayList.add(internalList.getString(internalList.getColumnIndex(MediaStore.MediaColumns.DATA))); //add the item
    //          internalList.moveToNext();
    //    }
    // }

    return arrayList;//gson.toJson(arrayList);
}

From source file:at.bitfire.davdroid.resource.LocalCollection.java

/**
 * Finds deleted resources (resources which have been marked for deletion).
 * Deleted resources have the "deleted" flag set.
 * Only records matching sqlFilter will be returned.
 * /*  w w  w. j  a  v a2  s  .c  o m*/
 * @return IDs of deleted resources
 * @throws LocalStorageException when the content provider couldn't be queried
 */
public long[] findDeleted() throws LocalStorageException {
    String where = entryColumnDeleted() + "=1";
    if (entryColumnParentID() != null)
        where += " AND " + entryColumnParentID() + "=" + String.valueOf(getId());
    if (sqlFilter != null)
        where += " AND (" + sqlFilter + ")";
    try {
        @Cleanup
        Cursor cursor = providerClient.query(entriesURI(),
                new String[] { entryColumnID(), entryColumnRemoteName(), entryColumnETag() }, where, null,
                null);
        if (cursor == null)
            throw new LocalStorageException("Couldn't query dirty records");

        long deleted[] = new long[cursor.getCount()];
        for (int idx = 0; cursor.moveToNext(); idx++)
            deleted[idx] = cursor.getLong(0);
        return deleted;
    } catch (RemoteException ex) {
        throw new LocalStorageException(ex);
    }
}

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

public String getName(String buddyId) {
    int index = buddyId.indexOf('@');
    if (index > -1)
        buddyId = buddyId.substring(0, index);
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    String where = MessageHistoryContract.ChatEntry.COLUMN_NAME_BUDDY_ID + "=?";
    Cursor c = db.query(MessageHistoryContract.ChatEntry.TABLE_NAME_ALL_CHATS,
            new String[] { MessageHistoryContract.ChatEntry.COLUMN_NAME_NAME }, where, new String[] { buddyId },
            null, null, null);//from  ww  w . ja  v a2 s.  co  m
    c.moveToFirst();
    String result = null;
    if (c.getCount() >= 1) {
        try {
            result = c.getString(0);
        } catch (Exception e) {
            result = buddyId;
        }
    }
    db.close();
    c.close();
    //    Log.d("MH_DEBUG", result);
    return result;
}

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

private ContentProviderResult[] optimisticallyCreateGroupAndContacts(JSONObject group,
        ContentProviderClient provider, ContentProviderClient contactsProvider, String authToken,
        Account account, SyncResult syncResult)
        throws JSONException, RemoteException, OperationApplicationException {

    String groupCloudId = group.getString(JSONKeys.KEY_ID);
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    // If the first operation asserts, that means the group already exists
    // Operation 0
    ContentProviderOperation.Builder op = ContentProviderOperation.newAssertQuery(GMSGroups.CONTENT_URI)
            .withValue(GMSGroup._ID, "").withValue(GMSGroup.CLOUD_ID, "")
            .withSelection(GMSGroup.CLOUD_ID + "=?", new String[] { groupCloudId }).withExpectedCount(0);
    ops.add(op.build());/*from   w w  w . j  av  a2s.co m*/
    // If we get this far, create the group from the information the JSON object
    // Operation 1
    ContentValues groupValues = GMSApplication.getGroupValues(group);
    op = ContentProviderOperation.newInsert(GMSGroups.CONTENT_URI).withValues(groupValues)
            .withValue(GMSGroup.STATUS, GMSGroup.STATUS_SYNCED);
    ops.add(op.build());
    // And add the contacts
    // Operations 2 - N + 2 where N is the number of members in group
    if (group.has(JSONKeys.KEY_MEMBERS)) {
        JSONArray membersArray = group.getJSONArray(JSONKeys.KEY_MEMBERS);
        int numMembers = membersArray.length();
        for (int j = 0; j < numMembers; ++j) {
            JSONObject member = membersArray.getJSONObject(j);
            ContentValues memberValues = GMSApplication.getMemberValues(member);
            op = ContentProviderOperation.newInsert(GMSContacts.CONTENT_URI).withValues(memberValues)
                    .withValueBackReference(GMSContact.GROUP_ID, 1)
                    .withValue(GMSContact.STATUS, GMSContact.STATUS_SYNCED);
            ops.add(op.build());
        }
    }
    ContentProviderResult[] results = provider.applyBatch(ops);
    // Create the contact on the device
    Uri groupUri = results[1].uri;
    if (groupUri != null) {
        Cursor cursor = null;
        try {
            cursor = GMSContactOperations.findGroupInContacts(contactsProvider, account, groupCloudId);
            if (cursor.getCount() > 0) {
                Assert.assertTrue(cursor.moveToFirst());
                long oldContactId = cursor.getLong(0);
                GMSContactOperations.removeGroupFromContacts(contactsProvider, account, oldContactId,
                        syncResult);
            }
            long contactId = GMSContactOperations.addGroupToContacts(getContext(), contactsProvider, account,
                    group, syncResult);
            if (contactId > 0) {
                ContentValues values = new ContentValues();
                values.put(GMSGroup.RAW_CONTACT_ID, contactId);
                provider.update(groupUri, values, null, null);
                addNewGroupNotification(group);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    return results;
}

From source file:at.bitfire.davdroid.resource.LocalCollection.java

/**
 * Finds updated resources (resources which have already been uploaded, but have changed locally).
 * Updated resources are 1) dirty, and 2) already have an ETag. Only records matching sqlFilter
 * will be returned./*from www  .  j  a  va2s. c  om*/
 * 
 * @return IDs of updated resources
 * @throws LocalStorageException when the content provider couldn't be queried
 */
public long[] findUpdated() throws LocalStorageException {
    String where = entryColumnDirty() + "=1 AND " + entryColumnETag() + " IS NOT NULL";
    if (entryColumnParentID() != null)
        where += " AND " + entryColumnParentID() + "=" + String.valueOf(getId());
    if (sqlFilter != null)
        where += " AND (" + sqlFilter + ")";
    try {
        @Cleanup
        Cursor cursor = providerClient.query(entriesURI(),
                new String[] { entryColumnID(), entryColumnRemoteName(), entryColumnETag() }, where, null,
                null);
        if (cursor == null)
            throw new LocalStorageException("Couldn't query updated records");

        long[] updated = new long[cursor.getCount()];
        for (int idx = 0; cursor.moveToNext(); idx++)
            updated[idx] = cursor.getLong(0);
        return updated;
    } catch (RemoteException ex) {
        throw new LocalStorageException(ex);
    }
}

From source file:fr.openbike.android.database.OpenBikeDBAdapter.java

public void cleanAndInsertStations(long version, JSONArray jsonBikes) throws JSONException {
    if ("".equals(jsonBikes))
        return;//from  ww  w  .ja  v a2s  .co  m
    Cursor favorites = getFilteredStationsCursor(new String[] { BaseColumns._ID }, KEY_FAVORITE + " = 1", null);
    // Get count : hack for forcing cursor query
    favorites.getCount();
    int network = jsonBikes.getJSONObject(0).getInt(Station.NETWORK);
    mDb.delete(STATIONS_TABLE, KEY_NETWORK + " = ?", new String[] { String.valueOf(network) });
    mDb.delete(STATIONS_VIRTUAL_TABLE, KEY_NETWORK + " = ?", new String[] { String.valueOf(network) });
    insertStations(jsonBikes);
    while (favorites.moveToNext()) {
        updateFavorite(favorites.getInt(0), true);
    }
    favorites.close();
    mPreferences.edit().putLong(AbstractPreferencesActivity.STATIONS_VERSION, version).commit();
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

private static long lookupContact(ContentResolver resolver, String name, String fb_id, boolean joinById,
        boolean syncAll) {
    Cursor c;

    if (joinById) {
        c = resolver.query(ContactsContract.Data.CONTENT_URI, //table
                new String[] { ContactsContract.Data.RAW_CONTACT_ID }, //select (projection)
                ContactsContract.Data.MIMETYPE + "=? AND " + CommonDataKinds.Note.NOTE + " LIKE ?", //where
                new String[] { ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE, "%" + fb_id + "%" }, //params
                null //sort
        );/*from w  w w.j  ava  2  s.  com*/
        try {
            if (c != null && c.moveToFirst()) {
                return c.getLong(0);
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
    }

    if (syncAll) {
        return -1;
    }

    c = resolver.query(Contacts.CONTENT_URI, //table
            new String[] { Contacts._ID }, //select (projection)
            Contacts.DISPLAY_NAME + "=?", //where
            new String[] { name }, //params
            null //sort
    );
    try {
        if (c != null && c.getCount() > 0) {
            return 0;
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }

    return -1;
}

From source file:fr.openbike.android.database.OpenBikeDBAdapter.java

public Cursor getNetwork(int id, String[] columns) {
    try {//from ww w  .ja  v a2s . com
        Cursor cursor = mDb.query(true, NETWORKS_TABLE, columns, BaseColumns._ID + " = ?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if ((cursor.getCount() == 0) || !cursor.moveToFirst()) {
            return null;
        }
        return cursor;
    } catch (Exception e) {
    }
    return null;
}

From source file:com.polyvi.xface.extension.messaging.XMessagingExt.java

/**
 * ????/*from w w  w .j ava2s .  co  m*/
 */
private int getRecordCount(Uri queryUri, String selection, String[] selectionArgs)
        throws InvalidParameterException {
    ContentResolver resolver = mContext.getContentResolver();
    Cursor cursor = resolver.query(queryUri, new String[] { BaseColumns._ID }, selection, selectionArgs, null);
    if (null == cursor) {
        throw new InvalidParameterException();
    }
    final int count = cursor.getCount();
    cursor.close();
    return count;
}

From source file:mobisocial.socialkit.musubi.Musubi.java

/**
 * Returns all DbIdentities owned by the current user
 *///from w  w  w  .  ja va 2  s .  c om
public List<DbIdentity> users(Uri feedUri) {
    Uri uri;
    if (feedUri == null) {
        uri = uriForDir(DbThing.IDENTITY);
    } else {
        long feedId = ContentUris.parseId(feedUri);
        uri = uriForItem(DbThing.MEMBER, feedId);
    }
    String selection = DbIdentity.COL_OWNED + " = 1";
    String[] selectionArgs = null;
    String sortOrder = null;
    Cursor c = mContext.getContentResolver().query(uri, DbIdentity.COLUMNS, selection, selectionArgs,
            sortOrder);
    try {
        List<DbIdentity> identities = new LinkedList<DbIdentity>();
        if (c == null || c.getCount() == 0) {
            Log.w(TAG, "no local user for feed " + feedUri, new Throwable());
            return identities;
        }
        while (c.moveToNext()) {
            DbIdentity id = DbIdentity.fromStandardCursor(mContext, c);
            identities.add(id);
        }
        return identities;
    } finally {
        if (c != null) {
            c.close();
        }
    }
}