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:mobisocial.musubi.service.AddressBookUpdateHandler.java

public static void importFullAddressBook(Context context) {
    Log.d(TAG, "doing full import");
    SQLiteOpenHelper db = App.getDatabaseSource(context);
    DatabaseManager dbm = new DatabaseManager(context);
    IdentitiesManager idm = dbm.getIdentitiesManager();
    FeedManager fm = dbm.getFeedManager();
    MyAccountManager am = dbm.getMyAccountManager();
    long startTime = System.currentTimeMillis();
    String musubiAccountType = context.getString(R.string.account_type);
    long maxDataId = -1;
    long maxContactId = -1;
    assert (SYNC_EMAIL);
    String account_type_selection = getAccountSelectionString();

    Cursor c = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
            new String[] { ContactsContract.Data.CONTACT_ID, ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.Data._ID, ContactsContract.Data.DATA_VERSION, ContactsContract.Data.DATA1,
                    ContactsContract.Data.MIMETYPE, ContactsContract.RawContacts.ACCOUNT_NAME,
                    ContactsContract.RawContacts.ACCOUNT_TYPE },
            "(" + ContactsContract.RawContacts.ACCOUNT_TYPE + "<>'" + musubiAccountType + "'" + ") AND ("
                    + NAME_OR_OTHER_SELECTION + account_type_selection + ")", // All known contacts.
            null, null);/*  w  w w  .j  av a2s  . co m*/

    if (c == null) {
        Log.e(TAG, "no valid cursor", new Throwable());
        return;
    }

    sAddressBookTotal = c.getCount();
    sAddressBookPosition = 0;
    Log.d(TAG, "Scanning contacts...");

    final Map<String, MMyAccount> myAccounts = new HashMap<String, MMyAccount>();
    final Pattern emailPattern = getEmailPattern();
    final Pattern numberPattern = getNumberPattern();
    while (c.moveToNext()) {
        sAddressBookPosition++;
        String identityType = c.getString(5);
        String identityPrincipal = c.getString(4);
        long contactId = c.getLong(0);
        long dataId = c.getLong(2);
        String displayName = c.getString(1);
        byte[] thumbnail = null;

        String accountName = c.getString(6);
        String accountType = c.getString(7);
        if (accountName == null) {
            accountName = "null-account-name";
        }
        if (accountType == null) {
            accountType = "null-account-type";
        }
        String accountKey = accountName + "-" + accountType;
        MMyAccount myAccount = myAccounts.get(accountKey);
        if (myAccount == null) {
            myAccount = lookupOrCreateAccount(dbm, accountName, accountType);
            prepareAccountWhitelistFeed(am, fm, myAccount);
            myAccounts.put(accountKey, myAccount);
        }

        if (displayName == null || emailPattern.matcher(displayName).matches()
                || numberPattern.matcher(displayName).matches()) {
            continue;
        }

        IBIdentity ibid = ibIdentityForData(identityType, identityPrincipal);
        if (ibid == null) {
            //TODO: better selection
            //Log.d(TAG, "skipping " + displayName + " // " + identityPrincipal);
            continue;
        }
        Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
        InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
                uri);
        if (is != null) {
            //Log.d(TAG, "importing photo for " + displayName);
            try {
                thumbnail = IOUtils.toByteArray(is);
            } catch (IOException e) {
                thumbnail = null;
                //Log.e(TAG, "photo thumbnail failed to serialize", e);
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        } else {
            thumbnail = null;
        }
        MIdentity ident = addIdentity(context, idm, contactId, displayName, thumbnail, ibid);
        if (ident != null) {
            fm.ensureFeedMember(myAccount.feedId_, ident.id_);
            fm.acceptFeedsFromMember(context, ident.id_);
        }

        maxDataId = Math.max(maxDataId, dataId);
        maxContactId = Math.max(maxContactId, contactId);
    }
    c.close();
    long timeTaken = System.currentTimeMillis() - startTime;

    ContactDataVersionManager cdvm = new ContactDataVersionManager(db);
    cdvm.setMaxDataIdSeen(maxDataId);
    cdvm.setMaxContactIdSeen(maxContactId);
    Log.d(TAG, "full import took " + timeTaken / 1000 + " secs");
    context.getContentResolver().notifyChange(MusubiService.ADDRESS_BOOK_SCANNED, null);
}

From source file:com.nonninz.robomodel.RoboManager.java

public long[] getSelectedModelIds(String selection, String[] selectionArgs, String groupBy, String having,
        String orderBy) {//  w w  w . j ava 2s.c o  m
    final SQLiteDatabase db = mDatabaseManager.openOrCreateDatabase(getDatabaseName());

    final String columns[] = new String[] { BaseColumns._ID };
    Cursor query;

    /*
     * Try the query. If the Table doesn't exist, fix the DB and re-run the query.
     */
    try {
        query = db.query(getTableName(), columns, selection, selectionArgs, groupBy, having, orderBy);
    } catch (final SQLiteException e) {
        prepareTable(db);
        query = db.query(getTableName(), columns, selection, selectionArgs, groupBy, having, orderBy);
    }

    final int columnIndex = query.getColumnIndex(BaseColumns._ID);
    final long result[] = new long[query.getCount()];
    for (query.moveToFirst(); !query.isAfterLast(); query.moveToNext()) {
        result[query.getPosition()] = query.getLong(columnIndex);
    }

    return result;
}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

/**
 * ???/* w  ww.ja va  2  s  .co  m*/
 *
 * @param type   FILE_URINATIVE_URI DATA_URL
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Cursor cursor = queryImgDB();
    int currentNumOfImages = 0;
    if (null != cursor) {
        currentNumOfImages = cursor.getCount();
    }

    if (type == FILE_URI || type == NATIVE_URI) {
        diff = 2;
    }

    // ??
    if ((currentNumOfImages - mNumPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
        Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id);
        getContext().getContentResolver().delete(uri, null, null);
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.MessagingManagerThread.java

@Override
public void run() {
    ProfileScanningObjHandler profileScanningObjHandler = new ProfileScanningObjHandler();
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Set<Long> notSendingObjects = new HashSet<Long>();
    if (DBG)//from   w w  w  . ja v  a 2 s . co  m
        Log.i(TAG, "Running...");
    mMessenger.init();
    long max_sent = -1;
    while (!interrupted()) {
        mOco.waitForChange();
        mOco.clearChanged();
        Cursor objs = mHelper.queryUnsentObjects(max_sent);
        try {
            Log.i(TAG, "Sending " + objs.getCount() + " objects...");
            if (objs.moveToFirst())
                do {
                    Long objId = objs.getLong(objs.getColumnIndexOrThrow(DbObject._ID));
                    String jsonSrc = objs.getString(objs.getColumnIndexOrThrow(DbObject.JSON));

                    max_sent = objId.longValue();
                    JSONObject json = null;
                    if (jsonSrc != null) {
                        try {
                            json = new JSONObject(jsonSrc);
                        } catch (JSONException e) {
                            Log.e(TAG, "bad json", e);
                        }
                    } else {
                        json = new JSONObject();
                    }

                    if (json != null) {
                        /*
                         * if you update latest feed here then there is a
                         * race condition between when you put a message
                         * into your db, when you actually have a connection
                         * to send the message (which is here) when other
                         * people send you messages the processing gets all
                         * out of order, so instead we update latest
                         * immediately when you add messages into your db
                         * inside DBHelper.java addToFeed();
                         */
                        // mFeedModifiedObjHandler.handleObj(mContext,
                        // feedUri, objId);

                        // TODO: Don't be fooled! This is not truly an
                        // EncodedObj
                        // and does not yet have a hash.
                        DbObj signedObj = App.instance().getMusubi().objForId(objId);
                        if (signedObj == null) {
                            Log.e(TAG, "Error, object " + objId + " not found in database");
                            notSendingObjects.add(objId);
                            continue;
                        }
                        DbEntryHandler h = DbObjects.getObjHandler(json);
                        h.afterDbInsertion(mContext, signedObj);

                        // TODO: Constraint error thrown for now b/c local
                        // user not in contacts
                        profileScanningObjHandler.handleObj(mContext, h, signedObj);
                    }

                    OutgoingMessage m = new OutgoingMsg(objs);
                    if (m.contents().getRecipients().isEmpty()) {
                        Log.w(TAG, "No addressees for direct message " + objId);
                        notSendingObjects.add(objId);
                    } else {
                        mMessenger.sendMessage(m);
                    }
                } while (objs.moveToNext());
            if (notSendingObjects.size() > 0) {
                if (DBG)
                    Log.d(TAG, "Marking " + notSendingObjects.size() + " objects sent");
                mHelper.markObjectsAsSent(notSendingObjects);
                notSendingObjects.clear();
            }
        } catch (Exception e) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                Log.wtf(TAG, "error running notify loop", e);
            } else {
                Log.e(TAG, "error running notify loop", e);
            }
        } finally {
            objs.close();
        }
    }
    mHelper.close();
}

From source file:com.odkclinic.client.PatientList.java

private void fillData() {
    // get cursor to list of patients
    Cursor patientCursor = mDb.getPatientList();
    startManagingCursor(patientCursor);/* ww  w . ja  v a2 s  .co  m*/

    // cache group id
    mGroupIdColumnIndex = patientCursor.getColumnIndexOrThrow(PatientTable.ID.getName());

    Log.d(LOG_TAG, "There are " + patientCursor.getCount() + " patients.");

    // create listadapter for cursor
    mAdapter = new ExpandablePatientListAdapter(patientCursor, this, R.layout.patientlist_group_item,
            R.layout.patientlist_child_item,
            new String[] { PatientTable.NAME.getName(), PatientTable.ID.getName(),
                    CohortMemberTable.COHORT_ID.getName() },
            new int[] { R.id.patient_name, R.id.patient_id, R.id.cohort_id },
            new String[] { PatientTable.GENDER.getName(), PatientTable.RACE.getName(),
                    PatientTable.BIRTHDATE.getName() },
            new int[] { R.id.patientgender, R.id.patientrace, R.id.patientbirthdate });

    setListAdapter(mAdapter);
}

From source file:mobisocial.bento.todo.io.BentoManager.java

synchronized public Bitmap getTodoBitmap(Uri objUri, String todoUuid, int targetWidth, int targetHeight,
        float degrees) {
    Bitmap bitmap = null;// ww w .  j ava  2s  . co  m

    DbFeed dbFeed = mMusubi.objForUri(objUri).getSubfeed();

    Cursor c = dbFeed.query();
    c.moveToFirst();
    for (int i = 0; i < c.getCount(); i++) {
        Obj object = mMusubi.objForCursor(c);
        if (object != null && object.getJson() != null && object.getJson().has(TODO_IMAGE)) {
            JSONObject diff = object.getJson().optJSONObject(TODO_IMAGE);
            if (todoUuid.equals(diff.optString(TODO_IMAGE_UUID))) {
                byte[] byteArray = Base64.decode(object.getJson().optString(B64JPGTHUMB), Base64.DEFAULT);
                bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
                break;
            }
        }
        c.moveToNext();
    }
    c.close();

    if (bitmap != null) {
        bitmap = BitmapHelper.getResizedBitmap(bitmap, targetWidth, targetHeight, degrees);
    }

    return bitmap;
}

From source file:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Used to find out if we are in a situation where the Camera Intent adds to images
 * to the content store. If we are using a FILE_URI and the number of images in the DB
 * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
 *
 * @param type FILE_URI or DATA_URL/*from ww w . j ava  2 s.  c o  m*/
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();

    if (type == FILE_URI && this.saveToPhotoAlbum) {
        diff = 2;
    }

    // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        if (diff == 2) {
            id--;
        }
        Uri uri = Uri.parse(contentStore + "/" + id);
        this.cordova.getActivity().getContentResolver().delete(uri, null, null);
    }
}

From source file:com.urs.triptracks.TripUploader.java

@Override
protected Boolean doInBackground(Long... tripid) {
    // First, send the trip user asked for:
    Boolean result = uploadOneTrip(tripid[0]);

    // Then, automatically try and send previously-completed trips
    // that were not sent successfully.
    Vector<Long> unsentTrips = new Vector<Long>();

    mDb.openReadOnly();/*from   w  w  w  .j av a 2s . c  o m*/
    Cursor cur = mDb.fetchUnsentTrips();
    if (cur != null && cur.getCount() > 0) {
        //pd.setMessage("Sent. You have previously unsent trips; submitting those now.");
        while (!cur.isAfterLast()) {
            //HS-unsentTrips.add(new Long(cur.getLong(0)));Use Long.valueOf(cur.getLong(0)) instead
            unsentTrips.add(Long.valueOf(cur.getLong(0)));
            cur.moveToNext();
        }
        cur.close();
    }
    mDb.close();

    for (Long trip : unsentTrips) {
        result &= uploadOneTrip(trip);
    }
    return result;
}

From source file:org.smap.smapTask.android.tasks.DownloadTasksTask.java

private Outcome submitCompletedForms() {

    String selection = InstanceColumns.SOURCE + "=? and (" + InstanceColumns.STATUS + "=? or "
            + InstanceColumns.STATUS + "=?)";
    String selectionArgs[] = { Utilities.getSource(), InstanceProviderAPI.STATUS_COMPLETE,
            InstanceProviderAPI.STATUS_SUBMISSION_FAILED };

    ArrayList<Long> toUpload = new ArrayList<Long>();
    Cursor c = null;
    try {/*from w w w .  ja v  a2 s . c  o m*/
        c = Collect.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection,
                selectionArgs, null);

        if (c != null && c.getCount() > 0) {
            c.move(-1);
            while (c.moveToNext()) {
                Long l = c.getLong(c.getColumnIndex(InstanceColumns._ID));
                toUpload.add(Long.valueOf(l));
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (c != null) {
            c.close();
        }
    }

    InstanceUploaderTask instanceUploaderTask = new InstanceUploaderTask();
    publishProgress("Submitting " + toUpload.size() + " finalised surveys");
    instanceUploaderTask.setUploaderListener((InstanceUploaderListener) mStateListener);

    Long[] toSendArray = new Long[toUpload.size()];
    toUpload.toArray(toSendArray);
    Log.i(getClass().getSimpleName(), "Submitting " + toUpload.size() + " finalised surveys");
    if (toUpload.size() > 0) {
        return instanceUploaderTask.doInBackground(toSendArray); // Already running a background task so call direct
    } else {
        return null;
    }

}

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

public MessageArrayContent[] getMessages(String buddyId, int amount, int offset, boolean reverse) {
    //Log.d("DATABASE", "Getting messages");
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    String[] columns = new String[] { MessageHistoryContract.MessageEntry.COLUMN_NAME_BUDDY_ID,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TYPE,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_CONTENT,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_URL,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_STATUS,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP,
            MessageHistoryContract.MessageEntry._ID,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_OTHERS_ID };
    Cursor messages = db.query(buddyId, columns, null, null, null, null,
            MessageHistoryContract.MessageEntry.COLUMN_NAME_MESSAGE_TIMESTAMP + " DESC", offset + "," + amount);

    if (reverse)/*from  ww w .j  av a 2 s. c o m*/
        messages.moveToFirst();
    else
        messages.moveToLast();
    int messageCount = messages.getCount();
    MessageArrayContent[] result = new MessageArrayContent[messageCount];
    int i = 0;
    if (messages.getCount() > 0)
        do {
            String from = messages.getString(0);
            SharedPreferences preferences = context.getSharedPreferences(Constants.PREFERENCES, 0);
            String me = preferences.getString(Constants.USERNAME, "");
            String type = messages.getString(1);
            String content = messages.getString(2);
            String url = messages.getString(3);
            int progress = 0;
            String status = messages.getString(4);
            long time = messages.getLong(5);
            long _ID = messages.getLong(6);
            long othersId = messages.getLong(7);
            switch (type) {
            case (MessageHistory.TYPE_TEXT):
                result[i] = new TextMessage(!me.equals(from), content, time, status, _ID, othersId);
                //            if (((TextMessage) result[i]).left)
                //              updateMessageStatus(from, _ID, STATUS_READ);
                break;
            case (MessageHistory.TYPE_IMAGE):
                try {
                    JSONArray contentJSON = new JSONArray(content);
                    result[i] = new ImageMessage(!me.equals(from), //left
                            contentJSON.getString(0), //File
                            contentJSON.getString(1), //description
                            url, //url
                            progress, //progress
                            time, //timeStamp
                            status, //status
                            _ID, //_ID
                            buddyId, //buddyID
                            othersId); //othersId
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            i++;
        } while (messages.move((reverse) ? 1 : -1));
    db.close();
    messages.close();
    return result;
}