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.wso2.mobile.mdm.api.TrackCallSMS.java

/**
 * Returns a JSONArray of SMS objects Ex: [{number:"0772345666", date:"dd/MM/yyyy hh:mm:ss.SSS", content:"Hello"}]
 * /*from   w  w w .j a  v  a  2  s  .com*/
 * @param type
 *            - Folder type should be passed in (1 for Inbox, 2 for Sent box)
 */
public JSONArray getSMS(int type) {
    JSONArray jsonArray = null;
    try {
        Uri uriSms = Uri.parse("content://sms");

        Cursor cursor = cr.query(uriSms, new String[] { "_id", "address", "date", "body", "type", "read" },
                "type=" + type, null, "date" + " COLLATE LOCALIZED ASC");

        if (cursor != null) {
            cursor.moveToLast();
            if (cursor.getCount() > 0) {
                jsonArray = new JSONArray();
                do {
                    JSONObject jsonObj = new JSONObject();
                    String date = cursor.getString(cursor.getColumnIndex("date"));
                    Long timestamp = Long.parseLong(date);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(timestamp);
                    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
                    jsonObj.put("number", cursor.getString(cursor.getColumnIndex("address")));
                    jsonObj.put("date", formatter.format(calendar.getTime()));
                    /*jsonObj.put("content",
                          cursor.getString(cursor.getColumnIndex("body")));*/
                    //jsonObj.put("content","Testing SMS");
                    jsonArray.add(jsonObj);
                } while (cursor.moveToPrevious());
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return jsonArray;

}

From source file:com.googlecode.android_scripting.facade.ContactsFacade.java

@Rpc(description = "Returns the number of contacts.")
public Integer contactsGetCount() {
    Integer result = 0;/*from  w  ww  . ja  v a  2 s .c  om*/
    Cursor cursor = mContentResolver.query(CONTACTS_URI, null, null, null, null);
    if (cursor != null) {
        result = cursor.getCount();
        cursor.close();
    }
    return result;
}

From source file:jp.ac.tokushima_u.is.ll.io.LanguageJsonHandler.java

public ArrayList<ContentProviderOperation> parse(ContentResolver resolver) {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    Uri uri = Languages.CONTENT_URI;
    String sortOrder = SyncColumns.UPDATED + " desc";
    Cursor cursor = resolver.query(uri, LanguagesQuery.PROJECTION, null, null, sortOrder);
    try {//  w w  w.jav  a 2 s  .  c o  m
        if (cursor.moveToFirst()) {
            Log.d(TAG, "Language has been inserted");
            int count = cursor.getCount();
            if (count > 3) {
                return batch;
            }
        }
    } finally {
        cursor.close();
    }

    HttpPost httpPost = new HttpPost(this.systemUrl + this.syncServiceUrl + this.languageSearchUrl);
    try {
        DefaultHttpClient client = HttpClientFactory.createHttpClient();
        MultipartEntity params = new MultipartEntity();
        httpPost.setEntity(params);
        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            String result = convertStreamToString(instream);
            instream.close();
            JSONObject json = new JSONObject(result);
            if (json != null) {
                JSONArray array = json.getJSONArray("languages");
                if (array != null) {
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject o = array.getJSONObject(i);
                        String languageId = o.getString("id");
                        if (languageId == null || languageId.length() <= 0)
                            continue;

                        ContentProviderOperation.Builder builder = ContentProviderOperation
                                .newInsert(Languages.CONTENT_URI);

                        builder.withValue(Languages.LANGUAGE_ID, languageId);
                        if (o.getString("code") != null && o.getString("code").length() > 0
                                && !"null".equals(o.getString("code")))
                            builder.withValue(Languages.CODE, o.getString("code"));
                        if (o.getString("name") != null && o.getString("name").length() > 0
                                && !"null".equals(o.getString("name")))
                            builder.withValue(Languages.NAME, o.getString("name"));
                        builder.withValue(SyncColumns.UPDATED, Calendar.getInstance().getTimeInMillis());
                        batch.add(builder.build());
                    }
                }
            }
        }
    } catch (Exception e) {
        Log.d(TAG, "exception occured", e);
    }

    return batch;
}

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

public static void updateContactPhotoHd(Context context, ContentResolver resolver, long rawContactId,
        ContactPhoto photo, BatchOperation batchOperation) {
    final Cursor c = resolver.query(DataQuery.CONTENT_URI, DataQuery.PROJECTION,
            Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?",
            new String[] { String.valueOf(rawContactId), Photo.CONTENT_ITEM_TYPE }, null);
    final ContactOperations contactOp = ContactOperations.updateExistingContact(context, rawContactId, true,
            batchOperation);/*w  ww . j a v a 2  s  .  c om*/

    if ((c != null) && c.moveToFirst()) {
        final long id = c.getLong(DataQuery.COLUMN_ID);
        final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, id);
        contactOp.updateAvatar(c.getString(DataQuery.COLUMN_DATA1), photo.getPhotoUrl(), uri);
        c.close();
    } else {
        Log.i(TAG, "creating row, count: " + c.getCount());
        contactOp.addAvatar(photo.getPhotoUrl());
    }
    Log.d(TAG, "updating check timestamp");
    final Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
    contactOp.updateSyncTimestamp1(System.currentTimeMillis(), uri);
}

From source file:com.jaspersoft.android.jaspermobile.util.SavedItemHelper.java

public boolean itemExist(String name, String format) {
    String selection = SavedItemsTable.NAME + " =? AND " + SavedItemsTable.FILE_FORMAT + " =?";
    Cursor cursor = context.getContentResolver().query(MobileDbProvider.SAVED_ITEMS_CONTENT_URI,
            new String[] { SavedItemsTable._ID }, selection, new String[] { name, format }, null);
    boolean itemExist = cursor != null && cursor.getCount() != 0;
    if (cursor != null) {
        cursor.close();/*from   w  w  w.java  2s . c  o m*/
    }
    return itemExist;
}

From source file:com.jaspersoft.android.jaspermobile.db.migrate.SavedItemsMigrationV3Test.java

@Test
public void savedItemsShouldBeMigratedToDatabase() throws IOException {
    File savedItemsDir = createSavedReportsDir();
    populateSavedReportsDir(savedItemsDir);

    migration.migrate(database);/*from  www .  java  2  s .  co m*/

    Cursor cursor = database.query("saved_items", new String[] { "_id", "file_path", "name", "file_format",
            "wstype", "account_name", "creation_time" }, null, null, null, null, null);
    assertThat(cursor, notNullValue());
    assertThat(cursor.getCount(), is(2));

    File sharedDir = new File(savedItemsDir, SHARED_DIR);
    File[] savedReportsDirs = sharedDir.listFiles();

    for (int i = 0; i < savedReportsDirs.length; i++) {
        File reportDir = savedReportsDirs[i];
        File report = new File(reportDir, reportDir.getName());
        assertThat(cursor.moveToPosition(i), is(true));

        String fileName = FileUtils.getBaseName(report.getName());
        String fileFormat = FileUtils.getExtension(report.getName()).toUpperCase(Locale.getDefault());
        long creationTime = reportDir.lastModified();

        assertThat(reportDir.listFiles().length, is(2));
        assertThat(cursor.getString(cursor.getColumnIndex("file_path")), is(report.getPath()));
        assertThat(cursor.getString(cursor.getColumnIndex("name")), is(fileName));
        assertThat(cursor.getString(cursor.getColumnIndex("file_format")), is(fileFormat));
        assertThat(cursor.getString(cursor.getColumnIndex("wstype")), is("unknown"));
        assertThat(cursor.getString(cursor.getColumnIndex("account_name")), is("com.jaspersoft.account.none"));
        assertThat(cursor.getString(cursor.getColumnIndex("creation_time")), is(String.valueOf(creationTime)));
    }
}

From source file:co.mwater.foregroundcameraplugin.ForegroundCameraLauncher.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.//from  w w w  .ja  va 2 s. c  o  m
 */
private void checkForDuplicateImage() {
    int diff = 2;
    Cursor cursor = queryImgDB();
    int currentNumOfImages = cursor.getCount();

    // 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))) - 1;
        Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id);
        this.cordova.getActivity().getContentResolver().delete(uri, null, null);
    }
}

From source file:edu.cwru.apo.Directory.java

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btnCall:
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + lastPhone));
        startActivity(intent);//from   w ww. j a  v  a2s.  co m
        break;

    case R.id.btnText:
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", lastPhone, null)));
        break;

    default:
        String text = ((TextView) v).getText().toString();
        int start = text.lastIndexOf('[');
        int end = text.lastIndexOf(']');
        String caseID = text.substring(start + 1, end);
        Cursor results = database.query("phoneDB", new String[] { "first", "last", "_id", "phone" }, "_id = ?",
                new String[] { caseID }, null, null, null);
        if (results.getCount() != 1) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Error Loading Phone Number").setCancelable(false).setNeutralButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            results.moveToFirst();

            phoneDialog = new Dialog(this);
            phoneDialog.setContentView(R.layout.phone_dialog);
            phoneDialog.setTitle(results.getString(0) + " " + results.getString(1));

            TextView phoneText = (TextView) phoneDialog.findViewById((R.id.phoneText));
            String phoneNumber = removeNonDigits(results.getString(3));
            if (phoneNumber == null || phoneNumber.trim().equals("") || phoneNumber.trim().equals("null")) {
                ((Button) phoneDialog.findViewById(R.id.btnCall)).setEnabled(false);
                ((Button) phoneDialog.findViewById(R.id.btnText)).setEnabled(false);
                phoneNumber = "not available";
            } else {
                ((Button) phoneDialog.findViewById(R.id.btnCall)).setEnabled(true);
                ((Button) phoneDialog.findViewById(R.id.btnText)).setEnabled(true);
                ((Button) phoneDialog.findViewById(R.id.btnCall)).setOnClickListener(this);
                ((Button) phoneDialog.findViewById(R.id.btnText)).setOnClickListener(this);
            }
            lastPhone = phoneNumber;
            phoneText.setText("Phone Number: " + lastPhone);
            phoneDialog.show();
        }
        break;
    }
}

From source file:com.socialize.util.ImageUtils.java

public int getOrientation(Context context, Uri photoUri) {
    /* it's on the external media. */
    Cursor cursor = context.getContentResolver().query(photoUri,
            new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);

    if (cursor == null) {
        return 0;
    }/*w w w  .  j  a  va  2 s.  com*/

    if (cursor.getCount() != 1) {
        return -1;
    }

    cursor.moveToFirst();
    return cursor.getInt(0);
}

From source file:com.prey.json.actions.ContactsBackup.java

@TargetApi(Build.VERSION_CODES.ECLAIR)
public HashMap<String, String> contacts2(Context ctx) {
    HashMap<String, String> parametersMap = new HashMap<String, String>();
    String phoneNumber = null;//from  w w w . j  a  va  2 s.  co  m
    int phoneType;

    String email = null;
    int emailType;

    Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;

    String _ID = ContactsContract.Contacts._ID;

    String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;

    String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

    Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

    String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;

    String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
    String NUMBER_TYPE = ContactsContract.CommonDataKinds.Phone.TYPE;

    Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;

    String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;

    String DATA = ContactsContract.CommonDataKinds.Email.DATA;
    String DATATYPE = ContactsContract.CommonDataKinds.Email.TYPE;

    Cursor cursor = ctx.getContentResolver().query(CONTENT_URI, null, null, null, null);

    // Loop for every contact in the phone

    if (cursor.getCount() > 0) {

        int i = 0;
        while (cursor.moveToNext()) {

            String contact_id = cursor.getString(cursor.getColumnIndex(_ID));

            String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));

            int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));

            if (hasPhoneNumber > 0) {

                PreyLogger.i("____________");
                parametersMap.put("contacts_backup[" + i + "][display_name]", name);
                parametersMap.put("contacts_backup[" + i + "][nickname][name]", name);
                parametersMap.put("contacts_backup[" + i + "][nickname][label]", name);

                PreyLogger.i("contacts_backup[" + i + "][display_name]" + name);
                PreyLogger.i("contacts_backup[" + i + "][nickname][name]" + name);
                PreyLogger.i("contacts_backup[" + i + "][nickname][label]" + name);

                // Query and loop for every phone number of the contact

                Cursor phoneCursor = ctx.getContentResolver().query(PhoneCONTENT_URI, null,
                        Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);

                int j = 0;
                while (phoneCursor.moveToNext()) {

                    phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                    phoneType = phoneCursor.getInt(phoneCursor.getColumnIndex(NUMBER_TYPE));

                    parametersMap.put("contacts_backup[" + i + "][phones][" + j + "][number]", phoneNumber);
                    parametersMap.put("contacts_backup[" + i + "][phones][" + j + "][type]",
                            typePhone(phoneType));

                    PreyLogger.i("contacts_backup[" + i + "][phones][" + j + "][number]" + phoneNumber);
                    PreyLogger.i("contacts_backup[" + i + "][phones][" + j + "][type]" + typePhone(phoneType));

                    j++;

                } // while phone

                phoneCursor.close();

                // Query and loop for every email of the contact

                Cursor emailCursor = ctx.getContentResolver().query(EmailCONTENT_URI, null,
                        EmailCONTACT_ID + " = ?", new String[] { contact_id }, null);

                j = 0;
                while (emailCursor.moveToNext()) {

                    email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
                    emailType = emailCursor.getInt(emailCursor.getColumnIndex(DATATYPE));
                    parametersMap.put("contacts_backup[" + i + "][emails][" + j + "][address]", email);
                    parametersMap.put("contacts_backup[" + i + "][emails][" + j + "][type]",
                            typeMail(emailType));

                    PreyLogger.i("contacts_backup[" + i + "][emails][" + j + "][address]" + email);
                    PreyLogger.i("contacts_backup[" + i + "][emails][" + j + "][type]" + typeMail(emailType));
                    j++;
                } // while email

                emailCursor.close();
                i = i + 1;
            } // if hasPhoneNumber

        } // while cursor
          // 
    } // if cursor
    return parametersMap;

}