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:net.potterpcs.recipebook.RecipeData.java

public long getNumberOfRecipes() {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = db.query(RECIPES_TABLE, new String[] { "_id" }, null, null, null, null, null);
        long num = c.getCount();
        c.close();/*from w  ww  .j  av a 2s  .  c  o m*/
        return num;
    }
}

From source file:eu.codeplumbers.cosi.services.CosiContactService.java

private void readContactDatabase() {
    //Fetches the complete call log in descending order. i.e recent calls appears first.
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

        // // TODO: 11/11/16 remove before release
        new Delete().from(ContactDataPoint.class).execute();
        new Delete().from(Contact.class).execute();

        if (cur.getCount() > 0) {
            int cnt = 0, total = cur.getCount();
            while (cur.moveToNext()) {
                EventBus.getDefault().post(new ContactSyncEvent(SYNC_MESSAGE,
                        "Reading local contacts " + (cnt + 1) + "/" + total + "..."));

                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                String photo = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
                System.out.println("name : " + name + ", ID : " + id);

                //Contact contact = Contact.getByName(name);

                //if (contact == null) {
                Contact contact = new Contact();
                contact.setN(name);/*from  w w  w . j  a v a  2  s . co  m*/
                contact.setRevision(DateUtils.formatDate(new Date().getTime()));
                contact.setRemoteId("");
                contact.setTags(new JSONArray().toString());

                contact.setFn(name);
                if (photo != null) {
                    contact.setPhotoBase64(FileUtils.uriToBase64(this, photo));
                } else {
                    contact.setPhotoBase64("");
                }
                //} else {
                if ((contact.getPhotoBase64() == null || contact.getPhotoBase64().equalsIgnoreCase(""))
                        && photo != null) {
                    contact.setPhotoBase64(FileUtils.uriToBase64(this, photo));
                }
                //}

                contact.setSystemId(id);
                contact.setDeviceId(contact.getRemoteId().isEmpty() ? Device.registeredDevice().getLogin()
                        : contact.getDeviceId());
                contact.save();

                if (Integer.parseInt(
                        cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    // get the phone number
                    Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id },
                            null);
                    while (pCur.moveToNext()) {
                        String phone = pCur
                                .getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        System.out.println("phone " + phone);
                        if (!phone.isEmpty()) {
                            ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact, phone);
                            if (contactDataPoint == null) {
                                contactDataPoint = new ContactDataPoint();
                                contactDataPoint.setPref(false);
                                contactDataPoint.setType("tel");
                                contactDataPoint.setValue(phone);
                                contactDataPoint.setName("tel");
                                contactDataPoint.setContact(contact);
                                contactDataPoint.save();
                            }
                        }
                    }
                    pCur.close();

                }
                // get email and type

                Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { id }, null);
                while (emailCur.moveToNext()) {
                    // This would allow you get several email addresses
                    // if the email addresses were stored in an array
                    String email = emailCur
                            .getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    String emailType = emailCur
                            .getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));

                    System.out.println("Email " + email + " Email Type : " + emailType);

                    if (!email.isEmpty()) {
                        ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact, email);
                        if (contactDataPoint == null) {
                            contactDataPoint = new ContactDataPoint();
                            contactDataPoint.setPref(false);
                            contactDataPoint.setType(emailType);
                            contactDataPoint.setValue(email);
                            contactDataPoint.setName("email");
                            contactDataPoint.setContact(contact);
                            contactDataPoint.save();
                        }
                    }
                }
                emailCur.close();

                // Get note.......
                String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
                        + ContactsContract.Data.MIMETYPE + " = ?";
                String[] noteWhereParams = new String[] { id,
                        ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE };
                Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams,
                        null);
                if (noteCur.moveToFirst()) {
                    String note = noteCur
                            .getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
                    System.out.println("Note " + note);

                    if (!note.isEmpty()) {
                        ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact, note);
                        if (contactDataPoint == null) {
                            contactDataPoint = new ContactDataPoint();
                            contactDataPoint.setPref(false);
                            contactDataPoint.setType("note");
                            contactDataPoint.setValue(note);
                            contactDataPoint.setName("note");
                            contactDataPoint.setContact(contact);
                            contactDataPoint.save();
                        }
                    }
                }
                noteCur.close();

                //Get Postal Address....

                String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
                        + ContactsContract.Data.MIMETYPE + " = ?";
                String[] addrWhereParams = new String[] { id,
                        ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
                Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI, null, null, null, null);
                while (addrCur.moveToNext()) {
                    String poBox = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
                    String street = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
                    String city = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
                    String state = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
                    String postalCode = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
                    String country = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
                    String type = addrCur.getString(
                            addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));

                }
                addrCur.close();

                // Get Instant Messenger.........
                String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE
                        + " = ?";
                String[] imWhereParams = new String[] { id,
                        ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE };
                Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI, null, imWhere, imWhereParams, null);
                if (imCur.moveToFirst()) {
                    String imName = imCur
                            .getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
                    String imType;
                    imType = imCur.getString(imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));

                    if (!imName.isEmpty()) {
                        ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact, imName);
                        if (contactDataPoint == null) {
                            contactDataPoint = new ContactDataPoint();
                            contactDataPoint.setPref(false);
                            contactDataPoint.setType(imType);
                            contactDataPoint.setValue(imName);
                            contactDataPoint.setName("chat");
                            contactDataPoint.setContact(contact);
                            contactDataPoint.save();
                        }
                    }

                }
                imCur.close();

                // Get Organizations
                String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
                        + ContactsContract.Data.MIMETYPE + " = ?";
                String[] orgWhereParams = new String[] { id,
                        ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };
                Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI, null, orgWhere, orgWhereParams,
                        null);
                if (orgCur.moveToFirst()) {
                    String orgName = orgCur.getString(
                            orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
                    String title = orgCur.getString(
                            orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
                }
                orgCur.close();

                cnt++;
            }
        }

    } else {
        EventBus.getDefault()
                .post(new ContactSyncEvent(SERVICE_ERROR, getString(R.string.permission_denied_contacts)));
    }
}

From source file:com.polyvi.xface.extension.contact.XContactsExt.java

/**
 * ????json./*from   www .ja  va  2  s.  co  m*/
 *
 * @param requiredField
 *            ????
 * @param c
 *            
 * @param contactsMaxNum
 *            ?
 * @return ? JSON 
 */

private JSONArray populateContactArray(HashSet<String> requiredField, Cursor c, int contactsMaxNum) {
    String oldContactId = "";
    boolean newContact = true;

    JSONArray contacts = new JSONArray();
    JSONObject contact = new JSONObject();

    HashMap<String, Object> contactMap = new HashMap<String, Object>();

    // ??
    mContactAccessor.initQuantityOfFields(contactMap);

    if (c.getCount() > 0) {
        while (c.moveToNext() && (contacts.length() <= (contactsMaxNum - 1))) {
            String contactId = mContactAccessor.getContactId(c);
            String rawId = mContactAccessor.getRawId(c);
            try {
                //  oldContactId
                if (c.getPosition() == 0) {
                    oldContactId = contactId;
                }

                // contact ID?
                // ?Contact object contacts
                //  Contact object
                if (!oldContactId.equals(contactId)) {
                    hashMapToJson(requiredField, contactMap, contact);
                    contacts.put(contact);

                    // 
                    contact = new JSONObject();
                    contactMap.clear();

                    // ??
                    mContactAccessor.initQuantityOfFields(contactMap);
                    newContact = true;
                }

                // ?  ID  display name
                // ????
                if (newContact) {
                    newContact = false;
                    contact.put(XContactAccessor.LOGIC_FIELD_ID, contactId);
                    contact.put(XContactAccessor.LOGIC_FIELD_RAWID, rawId);
                }

                mContactAccessor.cursorToHashMap(contactMap, c);
            } catch (JSONException e) {
                XLog.e(CLASS_NAME, e.getMessage(), e);
            }

            oldContactId = contactId;
        }

        // Push?? contacts
        if (contacts.length() < contactsMaxNum) {
            hashMapToJson(requiredField, contactMap, contact);
            contacts.put(contact);
        }
    }
    return contacts;
}

From source file:net.potterpcs.recipebook.RecipeData.java

public String findCacheEntry(String uri) {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = db.query(CACHE_TABLE, CACHE_FIELDS, CT_URI + " = ?", new String[] { uri }, null, null, null);
        if (c.getCount() > 0) {
            c.moveToFirst();/* w  w w .  j a  v a 2 s. c  o  m*/
            String s = c.getString(c.getColumnIndex(CT_CACHED));
            c.close();
            return s;
        } else {
            c.close();
            return null;
        }
    }
}

From source file:Main.java

/**
 * Print the content of the cursor// w  w w .  j  av  a 2  s .  c  o m
 *
 * @param cursor, The cursor, which content needs to be printed
 * @param logTag, The log tag
 */
public static void printCursorContent(Cursor cursor, String logTag) {
    if (cursor == null) {
        Log.d(logTag, "Cursor is NULL!");
        return;
    }
    final int columnSpace = 2;
    ArrayList<Integer> columnWidth = new ArrayList<Integer>();
    for (int columnIndex = 0; columnIndex < cursor.getColumnCount(); columnIndex++) {
        String value = cursor.getColumnName(columnIndex);
        int maxWidth = value.length();
        if (cursor.moveToFirst()) {
            do {
                try {
                    value = cursor.getString(columnIndex);
                } catch (Exception e) {
                    value = "BLOB";
                    Log.d(logTag, "Get value from " + cursor.getColumnName(columnIndex) + " failed. Caused by "
                            + e.getLocalizedMessage());
                }
                if (!TextUtils.isEmpty(value) && value.length() > maxWidth) {
                    maxWidth = value.length();
                }
            } while (cursor.moveToNext());
        }
        columnWidth.add(maxWidth + columnSpace);
    }
    ArrayList<ArrayList<String>> tableContent = new ArrayList<ArrayList<String>>();
    for (int columnIndex = 0; columnIndex < cursor.getColumnCount(); columnIndex++) {
        ArrayList<String> columnContent = new ArrayList<String>();
        String value = cursor.getColumnName(columnIndex);
        columnContent.add(appendColumnSpaces(value, columnWidth.get(columnIndex)));
        if (cursor.moveToFirst()) {
            do {
                try {
                    value = cursor.getString(columnIndex);
                } catch (Exception e) {
                    value = "BLOB";
                }
                columnContent.add(appendColumnSpaces(value, columnWidth.get(columnIndex)));
            } while (cursor.moveToNext());
        }
        tableContent.add(columnContent);
    }
    // Including the header
    int maxRowIndex = cursor.getCount() + 1;
    for (int rowIndex = 0; rowIndex < maxRowIndex; rowIndex++) {
        StringBuilder rowValues = new StringBuilder();
        for (int columnIndex = 0; columnIndex < cursor.getColumnCount(); columnIndex++) {
            ArrayList<String> columnValues = tableContent.get(columnIndex);
            rowValues.append(columnValues.get(rowIndex));
        }
        Log.d(logTag, rowValues.toString());
    }
    // set the cursor back the first item
    cursor.moveToFirst();
}

From source file:ac.robinson.mediaphone.provider.NarrativeAdapter.java

public void bindView(View view, Context context, Cursor cursor) {
    NarrativeViewHolder holder = (NarrativeViewHolder) view.getTag();

    // only load column indices once
    if (mInternalIdIndex < 0) {
        mInternalIdIndex = cursor.getColumnIndexOrThrow(NarrativeItem.INTERNAL_ID);
        mCreationDateIndex = cursor.getColumnIndexOrThrow(NarrativeItem.DATE_CREATED);
        mSequenceIdIndex = cursor.getColumnIndexOrThrow(NarrativeItem.SEQUENCE_ID);
    }/*from w  ww  .j a  va 2  s .  com*/

    holder.narrativeInternalId = cursor.getString(mInternalIdIndex);
    holder.narrativeDateCreated = cursor.getLong(mCreationDateIndex);
    holder.narrativeSequenceId = cursor.getInt(mSequenceIdIndex);

    final BrowserActivity activity = mActivity;
    if (activity.getScrollState() == AbsListView.OnScrollListener.SCROLL_STATE_FLING
            || activity.isPendingIconsUpdate()) {
        holder.queryIcons = true;
        holder.frameList.setAdapter(mEmptyAdapter);
    } else {
        attachAdapter(holder);
        holder.queryIcons = false;
    }

    // alternating row colours
    int cursorPosition = cursor.getPosition();
    if ((cursor.getCount() - cursorPosition) % 2 == 0) { // so the colour stays the same when adding a new narrative
        holder.frameList.setBackgroundResource(
                mIsTemplateView ? R.color.template_list_dark : R.color.narrative_list_dark);
    } else {
        holder.frameList.setBackgroundResource(
                mIsTemplateView ? R.color.template_list_light : R.color.narrative_list_light);
    }
}

From source file:alaindc.memenguage.View.MainActivity.java

private void updateWordsList() {
    wordsListview = (ListView) findViewById(R.id.wordslistview);

    adapter = new WordsAdapter(this, crs, 0);

    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return dbmanager.getMatchingWords(String.valueOf(constraint));
        }/*from w w w.  java 2 s. c om*/
    });

    wordsListview.setAdapter(adapter);
    wordsListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
            Intent createWordIntentActivity = new Intent(MainActivity.this, CreateEditActivity.class);
            createWordIntentActivity.setAction(Constants.ACTION_EDIT_WORD);

            Cursor crs = (Cursor) arg0.getItemAtPosition(pos);
            createWordIntentActivity.putExtra(Constants.EXTRA_EDIT_ITA,
                    crs.getString(crs.getColumnIndex(Constants.FIELD_ITA)));
            createWordIntentActivity.putExtra(Constants.EXTRA_EDIT_ENG,
                    crs.getString(crs.getColumnIndex(Constants.FIELD_ENG)));
            createWordIntentActivity.putExtra(Constants.EXTRA_EDIT_ID, id);

            MainActivity.this.startActivity(createWordIntentActivity);
            return true;
        }
    });

    wordsListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
            crs = (Cursor) arg0.getItemAtPosition(pos);
            String text = "Memory level: " + crs.getInt(crs.getColumnIndex(Constants.FIELD_RATING)) + "/5";
            text = text + "\nLast edit: "
                    + Utils.getDate(crs.getLong(crs.getColumnIndex(Constants.FIELD_TIMESTAMP)));

            crs = dbmanager.getContextById(id);
            if (crs != null && crs.getCount() > 0) {
                crs.moveToFirst();
                String cont = crs.getString(crs.getColumnIndex(Constants.FIELD_CONTEXT));
                text = text + "\n\n" + ((cont.equals("")) ? "Add a context sentence" : "Context:\n" + cont);
            }

            Toast t = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
            t.setGravity(Gravity.TOP, 0, 250);
            t.show();
        }
    });

    //Toast.makeText(getApplicationContext(), adapter.getCount()+" words in Memenguage", Toast.LENGTH_SHORT).show();
}