Example usage for android.database Cursor getPosition

List of usage examples for android.database Cursor getPosition

Introduction

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

Prototype

int getPosition();

Source Link

Document

Returns the current position of the cursor in the row set.

Usage

From source file:com.ravi.apps.android.newsbytes.HeadlinesAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    // Extract the view holder.
    ViewHolder viewHolder = (ViewHolder) view.getTag();

    // Get the mark as favorite flag.
    int isFavorite = cursor.getInt(HeadlinesFragment.COL_IS_FAVORITE);

    // If it's marked as favorite load image from byte stream, else use Picasso for loading.
    if (isFavorite == 1) {
        // Get the thumbnail blob from cursor.
        byte[] thumbnailByteStream = cursor.getBlob(HeadlinesFragment.COL_THUMBNAIL);

        // Check if blob for thumbnail is non null.
        if (thumbnailByteStream != null) {
            // Get the thumbnail bitmap from byte array.
            Bitmap thumbnailBitmap = BitmapFactory.decodeByteArray(thumbnailByteStream, 0,
                    thumbnailByteStream.length);

            // Set the thumbnail bitmap into the image view.
            viewHolder.thumbnailView.setImageBitmap(thumbnailBitmap);
            viewHolder.thumbnailView.setScaleType(ImageView.ScaleType.FIT_XY);
        } else {// w w w  . ja  va  2 s .c om
            // Show thumbnail placeholder icon and log error message.
            viewHolder.thumbnailView.setImageResource(R.drawable.thumbnail_placeholder);
            Log.e(LOG_TAG, context.getString(R.string.msg_err_no_thumbnail));
        }
    } else {
        // Get the thumbnail uri.
        String urlThumbnail = cursor.getString(HeadlinesFragment.COL_URI_THUMBNAIL);

        // Check if url for thumbnail is non null.
        if (urlThumbnail != null) {
            // Remove escape characters from the string.
            String url = Utility.removeCharsFromString(urlThumbnail, "\\");

            // Load the thumbnail into image view using Picasso.
            Picasso.with(context).load(url).placeholder(R.drawable.thumbnail_placeholder).fit()
                    .into(viewHolder.thumbnailView);
        } else {
            // Show thumbnail placeholder icon and log error message.
            viewHolder.thumbnailView.setImageResource(R.drawable.thumbnail_placeholder);
            Log.e(LOG_TAG, context.getString(R.string.msg_err_no_thumbnail));
        }
    }

    // Get the headline and set it onto the text view.
    String headline = cursor.getString(HeadlinesFragment.COL_HEADLINE);

    // Check if headline is non null and non empty.
    if (headline != null && !headline.isEmpty()) {
        viewHolder.headlineView.setText(headline);
        viewHolder.headlineView.setContentDescription(headline);
    } else {
        // Display headline not available message and log error message.
        viewHolder.headlineView.setText(context.getString(R.string.msg_err_no_headline));
        viewHolder.headlineView.setContentDescription(context.getString(R.string.msg_err_no_headline));
        Log.e(LOG_TAG, context.getString(R.string.msg_err_no_headline));
    }

    // Generate transition names for shared elements for devices running lollipop or above.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        viewHolder.thumbnailView.setTransitionName(THUMBNAIL_TRANSITION_NAME + cursor.getPosition());
        viewHolder.headlineView.setTransitionName(HEADLINE_TRANSITION_NAME + cursor.getPosition());
    }
}

From source file:org.totschnig.myexpenses.activity.ExpenseEdit.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data == null) {
        return;/*from  w ww. j  a v a 2 s.  co  m*/
    }
    int id = loader.getId();
    switch (id) {
    case METHODS_CURSOR:
        mMethodsCursor = data;
        View methodContainer = findViewById(R.id.MethodRow);
        if (mMethodsAdapter == null || !data.moveToFirst()) {
            methodContainer.setVisibility(View.GONE);
        } else {
            methodContainer.setVisibility(View.VISIBLE);
            MatrixCursor extras = new MatrixCursor(new String[] { KEY_ROWID, KEY_LABEL, KEY_IS_NUMBERED });
            extras.addRow(new String[] { "0", "- - - -", "0" });
            mMethodsAdapter.swapCursor(new MergeCursor(new Cursor[] { extras, data }));
            if (mSavedInstance) {
                mTransaction.methodId = mMethodId;
            }
            if (mTransaction.methodId != null) {
                while (data.isAfterLast() == false) {
                    if (data.getLong(data.getColumnIndex(KEY_ROWID)) == mTransaction.methodId) {
                        mMethodSpinner.setSelection(data.getPosition() + 1);
                        break;
                    }
                    data.moveToNext();
                }
            } else {
                mMethodSpinner.setSelection(0);
            }
        }
        break;
    case ACCOUNTS_CURSOR:
        mAccountsAdapter.swapCursor(data);
        mAccounts = new Account[data.getCount()];
        if (mSavedInstance) {
            mTransaction.accountId = mAccountId;
            mTransaction.transfer_account = mTransferAccountId;
        }
        data.moveToFirst();
        boolean selectionSet = false;
        String currencyExtra = getIntent().getStringExtra(KEY_CURRENCY);
        while (data.isAfterLast() == false) {
            int position = data.getPosition();
            Account a = Account.fromCacheOrFromCursor(data);
            mAccounts[position] = a;
            if (!selectionSet && (a.currency.getCurrencyCode().equals(currencyExtra)
                    || (currencyExtra == null && a.getId().equals(mTransaction.accountId)))) {
                mAccountSpinner.setSelection(position);
                setAccountLabel(a);
                selectionSet = true;
            }
            data.moveToNext();
        }
        //if the accountId we have been passed does not exist, we select the first entry
        if (mAccountSpinner.getSelectedItemPosition() == android.widget.AdapterView.INVALID_POSITION) {
            mAccountSpinner.setSelection(0);
            mTransaction.accountId = mAccounts[0].getId();
            setAccountLabel(mAccounts[0]);
        }
        if (mOperationType == MyExpenses.TYPE_TRANSFER) {
            mTransferAccountCursor = new FilterCursorWrapper(data);
            int selectedPosition = setTransferAccountFilterMap();
            mTransferAccountsAdapter.swapCursor(mTransferAccountCursor);
            mTransferAccountSpinner.setSelection(selectedPosition);
            mTransaction.transfer_account = mTransferAccountSpinner.getSelectedItemId();
            configureTransferInput();
            if (!mNewInstance && !(mTransaction instanceof Template)) {
                isProcessingLinkedAmountInputs = true;
                mTransferAmountText.setAmount(mTransaction.getTransferAmount().getAmountMajor().abs());
                updateExchangeRates();
                isProcessingLinkedAmountInputs = false;
            }
        } else {
            //the methods cursor is based on the current account,
            //hence it is loaded only after the accounts cursor is loaded
            if (!(mTransaction instanceof SplitPartCategory)) {
                mManager.initLoader(METHODS_CURSOR, null, this);
            }
        }
        mTypeButton.setEnabled(true);
        configureType();
        configureStatusSpinner();
        if (mIsResumed)
            setupListeners();
        break;
    case LAST_EXCHANGE_CURSOR:
        if (data.moveToFirst()) {
            final Currency currency1 = getCurrentAccount().currency;
            final Currency currency2 = Account
                    .getInstanceFromDb(mTransferAccountSpinner.getSelectedItemId()).currency;
            if (currency1.getCurrencyCode().equals(data.getString(0))
                    && currency2.getCurrencyCode().equals(data.getString(1))) {
                BigDecimal amount = new Money(currency1, data.getLong(2)).getAmountMajor();
                BigDecimal transferAmount = new Money(currency2, data.getLong(3)).getAmountMajor();
                BigDecimal exchangeRate = amount.compareTo(nullValue) != 0
                        ? transferAmount.divide(amount, EXCHANGE_RATE_FRACTION_DIGITS, RoundingMode.DOWN)
                        : nullValue;
                if (exchangeRate.compareTo(nullValue) != 0) {
                    mExchangeRate1Text.setAmount(exchangeRate);
                }
            }
        }
    }
}

From source file:com.example.navigationsearchview.NavigationSearchView.java

/**
 * When a particular suggestion has been selected, perform the various
 * lookups required to use the suggestion. This includes checking the cursor
 * for suggestion-specific data, and/or falling back to the XML for
 * defaults; It also creates REST style Uri data when the suggestion
 * includes a data id./*from  w ww. ja v  a2 s  .c  om*/
 *
 * @param c
 *            The suggestions cursor, moved to the row of the user's
 *            selection
 * @param actionKey
 *            The key code of the action key that was pressed, or
 *            {@link KeyEvent#KEYCODE_UNKNOWN} if none.
 * @param actionMsg
 *            The message for the action key that was pressed, or
 *            <code>null</code> if none.
 * @return An intent for the suggestion at the cursor's position.
 */
private Intent createIntentFromSuggestion(Cursor c, int actionKey, String actionMsg) {
    try {
        // use specific action if supplied, or default action if supplied,
        // or fixed default
        String action = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_ACTION);

        if (action == null && Build.VERSION.SDK_INT >= 8) {
            action = mSearchable.getSuggestIntentAction();
        }
        if (action == null) {
            action = Intent.ACTION_SEARCH;
        }

        // use specific data if supplied, or default data if supplied
        String data = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA);
        if (IS_AT_LEAST_FROYO && data == null) {
            data = mSearchable.getSuggestIntentData();
        }
        // then, if an ID was provided, append it.
        if (data != null) {
            String id = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
            if (id != null) {
                data = data + "/" + Uri.encode(id);
            }
        }
        Uri dataUri = (data == null) ? null : Uri.parse(data);

        String query = getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY);
        String extraData = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);

        return createIntent(action, dataUri, extraData, query, actionKey, actionMsg);
    } catch (RuntimeException e) {
        int rowNum;
        try { // be really paranoid now
            rowNum = c.getPosition();
        } catch (RuntimeException e2) {
            rowNum = -1;
        }
        Log.w(LOG_TAG, "Search suggestions cursor at row " + rowNum + " returned exception.", e);
        return null;
    }
}

From source file:android.support.v7ox.widget.SearchView.java

/**
 * When a particular suggestion has been selected, perform the various lookups required
 * to use the suggestion.  This includes checking the cursor for suggestion-specific data,
 * and/or falling back to the XML for defaults;  It also creates REST style Uri data when
 * the suggestion includes a data id./*from ww  w.  ja va2  s  . com*/
 *
 * @param c The suggestions cursor, moved to the row of the user's selection
 * @param actionKey The key code of the action key that was pressed,
 *        or {@link KeyEvent#KEYCODE_UNKNOWN} if none.
 * @param actionMsg The message for the action key that was pressed,
 *        or <code>null</code> if none.
 * @return An intent for the suggestion at the cursor's position.
 */
private Intent createIntentFromSuggestion(Cursor c, int actionKey, String actionMsg) {
    try {
        // use specific action if supplied, or default action if supplied, or fixed default
        String action = SuggestionsAdapter.getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_ACTION);

        if (action == null && Build.VERSION.SDK_INT >= 8) {
            action = mSearchable.getSuggestIntentAction();
        }
        if (action == null) {
            action = Intent.ACTION_SEARCH;
        }

        // use specific data if supplied, or default data if supplied
        String data = SuggestionsAdapter.getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA);
        if (IS_AT_LEAST_FROYO && data == null) {
            data = mSearchable.getSuggestIntentData();
        }
        // then, if an ID was provided, append it.
        if (data != null) {
            String id = SuggestionsAdapter.getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
            if (id != null) {
                data = data + "/" + Uri.encode(id);
            }
        }
        Uri dataUri = (data == null) ? null : Uri.parse(data);

        String query = SuggestionsAdapter.getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY);
        String extraData = SuggestionsAdapter.getColumnString(c,
                SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);

        return createIntent(action, dataUri, extraData, query, actionKey, actionMsg);
    } catch (RuntimeException e) {
        int rowNum;
        try { // be really paranoid now
            rowNum = c.getPosition();
        } catch (RuntimeException e2) {
            rowNum = -1;
        }
        Log.w(LOG_TAG, "Search suggestions cursor at row " + rowNum + " returned exception.", e);
        return null;
    }
}

From source file:com.csipsimple.ui.favorites.FavAdapter.java

@Override
public void bindView(View view, final Context context, Cursor cursor) {
    ContentValues cv = new ContentValues();
    DatabaseUtils.cursorRowToContentValues(cursor, cv);

    int type = ContactsWrapper.TYPE_CONTACT;
    if (cv.containsKey(ContactsWrapper.FIELD_TYPE)) {
        type = cv.getAsInteger(ContactsWrapper.FIELD_TYPE);
    }//from  w w w  .  j  a va  2s  .  c  o  m

    showViewForType(view, type);

    if (type == ContactsWrapper.TYPE_GROUP) {
        // Get views
        TextView tv = (TextView) view.findViewById(R.id.header_text);
        ImageView icon = (ImageView) view.findViewById(R.id.header_icon);
        PresenceStatusSpinner presSpinner = (PresenceStatusSpinner) view
                .findViewById(R.id.header_presence_spinner);

        // Get datas
        SipProfile acc = new SipProfile(cursor);

        final Long profileId = cv.getAsLong(BaseColumns._ID);
        final String groupName = acc.android_group;
        final String displayName = acc.display_name;
        final String wizard = acc.wizard;
        final boolean publishedEnabled = (acc.publish_enabled == 1);
        final String domain = acc.getDefaultDomain();

        // Bind datas to view
        tv.setText(displayName);
        icon.setImageResource(WizardUtils.getWizardIconRes(wizard));
        presSpinner.setProfileId(profileId);

        // Extra menu view if not already set
        ViewGroup menuViewWrapper = (ViewGroup) view.findViewById(R.id.header_cfg_spinner);

        MenuCallback newMcb = new MenuCallback(context, profileId, groupName, domain, publishedEnabled);
        MenuBuilder menuBuilder;
        if (menuViewWrapper.getTag() == null) {

            final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.MATCH_PARENT);

            ActionMenuPresenter mActionMenuPresenter = new ActionMenuPresenter(mContext);
            mActionMenuPresenter.setReserveOverflow(true);
            menuBuilder = new MenuBuilder(context);
            menuBuilder.setCallback(newMcb);
            MenuInflater inflater = new MenuInflater(context);
            inflater.inflate(R.menu.fav_menu, menuBuilder);
            menuBuilder.addMenuPresenter(mActionMenuPresenter);
            ActionMenuView menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(menuViewWrapper);
            UtilityWrapper.getInstance().setBackgroundDrawable(menuView, null);
            menuViewWrapper.addView(menuView, layoutParams);
            menuViewWrapper.setTag(menuBuilder);
        } else {
            menuBuilder = (MenuBuilder) menuViewWrapper.getTag();
            menuBuilder.setCallback(newMcb);
        }
        menuBuilder.findItem(R.id.share_presence).setTitle(
                publishedEnabled ? R.string.deactivate_presence_sharing : R.string.activate_presence_sharing);
        menuBuilder.findItem(R.id.set_sip_data).setVisible(!TextUtils.isEmpty(groupName));

    } else if (type == ContactsWrapper.TYPE_CONTACT) {
        ContactInfo ci = ContactsWrapper.getInstance().getContactInfo(context, cursor);
        ci.userData = cursor.getPosition();
        // Get views
        TextView tv = (TextView) view.findViewById(R.id.contact_name);
        QuickContactBadge badge = (QuickContactBadge) view.findViewById(R.id.quick_contact_photo);
        TextView statusText = (TextView) view.findViewById(R.id.status_text);
        ImageView statusImage = (ImageView) view.findViewById(R.id.status_icon);

        // Bind
        if (ci.contactId != null) {
            tv.setText(ci.displayName);
            badge.assignContactUri(ci.callerInfo.contactContentUri);
            ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(context, badge.getImageView(),
                    ci.callerInfo, R.drawable.ic_contact_picture_holo_dark);

            statusText.setVisibility(ci.hasPresence ? View.VISIBLE : View.GONE);
            statusText.setText(ci.status);
            statusImage.setVisibility(ci.hasPresence ? View.VISIBLE : View.GONE);
            statusImage.setImageResource(ContactsWrapper.getInstance().getPresenceIconResourceId(ci.presence));
        }
        View v;
        v = view.findViewById(R.id.contact_view);
        v.setTag(ci);
        v.setOnClickListener(mPrimaryActionListener);
        v = view.findViewById(R.id.secondary_action_icon);
        v.setTag(ci);
        v.setOnClickListener(mSecondaryActionListener);
    } else if (type == ContactsWrapper.TYPE_CONFIGURE) {
        // We only bind if it's the correct type
        View v = view.findViewById(R.id.configure_view);
        v.setOnClickListener(this);
        ConfigureObj cfg = new ConfigureObj();
        cfg.profileId = cv.getAsLong(BaseColumns._ID);
        v.setTag(cfg);
    }
}

From source file:com.fututel.ui.favorites.FavAdapter.java

@Override
public void bindView(View view, final Context context, Cursor cursor) {
    ContentValues cv = new ContentValues();
    DatabaseUtils.cursorRowToContentValues(cursor, cv);

    int type = ContactsWrapper.TYPE_CONTACT;
    if (cv.containsKey(ContactsWrapper.FIELD_TYPE)) {
        type = cv.getAsInteger(ContactsWrapper.FIELD_TYPE);
    }//  w  w w  . ja v a  2  s .com

    showViewForType(view, type);

    if (type == ContactsWrapper.TYPE_GROUP) {
        // Get views
        TextView tv = (TextView) view.findViewById(R.id.header_text);
        ImageView icon = (ImageView) view.findViewById(R.id.header_icon);
        PresenceStatusSpinner presSpinner = (PresenceStatusSpinner) view
                .findViewById(R.id.header_presence_spinner);

        // Get datas
        SipProfile acc = new SipProfile(cursor);

        final Long profileId = cv.getAsLong(BaseColumns._ID);
        final String groupName = acc.android_group;
        final String displayName = acc.display_name;
        final String wizard = acc.wizard;
        final boolean publishedEnabled = (acc.publish_enabled == 1);
        final String domain = acc.getDefaultDomain();

        // Bind datas to view
        tv.setText(displayName);
        icon.setImageResource(WizardUtils.getWizardIconRes(wizard));
        presSpinner.setProfileId(profileId);

        // Extra menu view if not already set
        ViewGroup menuViewWrapper = (ViewGroup) view.findViewById(R.id.header_cfg_spinner);

        MenuCallback newMcb = new MenuCallback(context, profileId, groupName, domain, publishedEnabled);
        MenuBuilder menuBuilder;
        if (menuViewWrapper.getTag() == null) {

            final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.MATCH_PARENT);

            ActionMenuPresenter mActionMenuPresenter = new ActionMenuPresenter(mContext);
            mActionMenuPresenter.setReserveOverflow(true);
            menuBuilder = new MenuBuilder(context);
            menuBuilder.setCallback(newMcb);
            MenuInflater inflater = new MenuInflater(context);
            inflater.inflate(R.menu.fav_menu, menuBuilder);
            menuBuilder.addMenuPresenter(mActionMenuPresenter);
            ActionMenuView menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(menuViewWrapper);
            UtilityWrapper.getInstance().setBackgroundDrawable(menuView, null);
            menuViewWrapper.addView(menuView, layoutParams);
            menuViewWrapper.setTag(menuBuilder);
        } else {
            menuBuilder = (MenuBuilder) menuViewWrapper.getTag();
            menuBuilder.setCallback(newMcb);
        }
        menuBuilder.findItem(R.id.share_presence).setTitle(
                publishedEnabled ? R.string.deactivate_presence_sharing : R.string.activate_presence_sharing);
        menuBuilder.findItem(R.id.set_sip_data).setVisible(!TextUtils.isEmpty(groupName));

    } else if (type == ContactsWrapper.TYPE_CONTACT) {
        ContactInfo ci = ContactsWrapper.getInstance().getContactInfo(context, cursor);
        ci.userData = cursor.getPosition();
        // Get views
        TextView tv = (TextView) view.findViewById(R.id.contact_name);
        QuickContactBadge badge = (QuickContactBadge) view.findViewById(R.id.quick_contact_photo);
        TextView statusText = (TextView) view.findViewById(R.id.status_text);
        ImageView statusImage = (ImageView) view.findViewById(R.id.status_icon);

        // Bind
        if (ci.contactId != null) {
            tv.setText(ci.displayName);
            badge.assignContactUri(ci.callerInfo.contactContentUri);
            ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(context, badge.getImageView(),
                    ci.callerInfo, R.drawable.ic_contact_picture_holo_light);

            statusText.setVisibility(ci.hasPresence ? View.VISIBLE : View.GONE);
            statusText.setText(ci.status);
            statusImage.setVisibility(ci.hasPresence ? View.VISIBLE : View.GONE);
            statusImage.setImageResource(ContactsWrapper.getInstance().getPresenceIconResourceId(ci.presence));
        }
        View v;
        v = view.findViewById(R.id.contact_view);
        v.setTag(ci);
        v.setOnClickListener(mPrimaryActionListener);
        v = view.findViewById(R.id.secondary_action_icon);
        v.setTag(ci);
        v.setOnClickListener(mSecondaryActionListener);
    } else if (type == ContactsWrapper.TYPE_CONFIGURE) {
        // We only bind if it's the correct type
        View v = view.findViewById(R.id.configure_view);
        v.setOnClickListener(this);
        ConfigureObj cfg = new ConfigureObj();
        cfg.profileId = cv.getAsLong(BaseColumns._ID);
        v.setTag(cfg);
    }
}

From source file:com.karura.framework.plugins.utils.ContactAccessorSdk5.java

/**
 * Creates an array of contacts from the cursor you pass in
 * //from ww  w.  ja  v  a  2  s  .  c om
 * @param populate
 *            whether or not you should populate a certain value
 * @param c
 *            the cursor
 * @return a JSONArray of contacts
 */
private JSONArray populateContactArray(HashMap<String, Boolean> populate, Cursor c) {

    String contactId = "";
    String rawId = "";
    String oldContactId = "";
    boolean newContact = true;
    String mimetype = "";

    JSONArray contacts = new JSONArray();
    JSONObject contact = new JSONObject();
    JSONArray organizations = new JSONArray();
    JSONArray addresses = new JSONArray();
    JSONArray phones = new JSONArray();
    JSONArray emails = new JSONArray();
    JSONArray ims = new JSONArray();
    JSONArray websites = new JSONArray();
    JSONArray photos = new JSONArray();

    // Column indices
    int colContactId = c.getColumnIndex(ContactsContract.Data.CONTACT_ID);
    int colRawContactId = c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
    int colMimetype = c.getColumnIndex(ContactsContract.Data.MIMETYPE);
    int colDisplayName = c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
    int colNote = c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE);
    int colBirthday = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
    int colEventType = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE);
    int index = 0;
    if (c.getCount() > 0) {
        while (c.moveToNext()) {
            try {
                contactId = c.getString(colContactId);
                rawId = c.getString(colRawContactId);

                // If we are in the first row set the oldContactId
                if (c.getPosition() == 0) {
                    oldContactId = contactId;
                }

                // When the contact ID changes we need to push the Contact
                // object
                // to the array of contacts and create new objects.
                if (!oldContactId.equals(contactId)) {
                    // Populate the Contact object with it's arrays
                    // and push the contact into the contacts array
                    contacts.put(populateContact(contact, organizations, addresses, phones, emails, ims,
                            websites, photos));

                    // Clean up the objects
                    contact = new JSONObject();
                    organizations = new JSONArray();
                    addresses = new JSONArray();
                    phones = new JSONArray();
                    emails = new JSONArray();
                    ims = new JSONArray();
                    websites = new JSONArray();
                    photos = new JSONArray();

                    // Set newContact to true as we are starting to populate
                    // a new contact
                    newContact = true;
                }

                // When we detect a new contact set the ID and display name.
                // These fields are available in every row in the result set
                // returned.
                if (newContact) {
                    newContact = false;
                    contact.put("id", contactId);
                    contact.put("rawId", rawId);
                    contact.put("index", index++);
                }

                // Grab the mimetype of the current row as it will be used
                // in a lot of comparisons
                mimetype = c.getString(colMimetype);

                if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) {
                    contact.put(DISPLAY_NAME, c.getString(colDisplayName));
                }

                if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        && isRequired(NAME, populate)) {
                    contact.put(NAME, nameQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        && isRequired(PHONE_NUMBER, populate)) {
                    phones.put(phoneQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                        && isRequired(EMAIL, populate)) {
                    emails.put(emailQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                        && isRequired(FORMATTED_ADDRESS, populate)) {
                    addresses.put(addressQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                        && isRequired(ORGANIZATION, populate)) {
                    organizations.put(organizationQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
                        && isRequired(IMS, populate)) {
                    ims.put(imQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
                        && isRequired(NOTE, populate)) {
                    contact.put(NOTE, c.getString(colNote));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
                        && isRequired(URLS, populate)) {
                    websites.put(websiteQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)) {
                    if (isRequired(BIRTHDAY, populate)
                            && ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c.getInt(colEventType)) {
                        contact.put(BIRTHDAY, c.getString(colBirthday));
                    }
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                        && isRequired(PHOTO, populate)) {
                    photos.put(photoQuery(c, contactId));
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }

            // Set the old contact ID
            oldContactId = contactId;

        }

        contacts.put(populateContact(contact, organizations, addresses, phones, emails, ims, websites, photos));
    }
    c.close();
    return contacts;
}

From source file:com.roamprocess1.roaming4world.ui.favorites.FavAdapter.java

@Override
public void bindView(View view, final Context context, Cursor cursor) {
    ContentValues cv = new ContentValues();
    DatabaseUtils.cursorRowToContentValues(cursor, cv);

    int type = ContactsWrapper.TYPE_CONTACT;
    if (cv.containsKey(ContactsWrapper.FIELD_TYPE)) {
        type = cv.getAsInteger(ContactsWrapper.FIELD_TYPE);
    }//  w  w w . j  a  va  2s. c  om

    showViewForType(view, type);

    if (type == ContactsWrapper.TYPE_GROUP) {
        // Get views
        TextView tv = (TextView) view.findViewById(R.id.header_text);
        ImageView icon = (ImageView) view.findViewById(R.id.header_icon);
        //   PresenceStatusSpinner presSpinner = (PresenceStatusSpinner) view.findViewById(R.id.header_presence_spinner);

        // Get datas
        SipProfile acc = new SipProfile(cursor);

        final Long profileId = cv.getAsLong(BaseColumns._ID);
        final String groupName = acc.android_group;
        final String displayName = acc.display_name;
        final String wizard = acc.wizard;
        final boolean publishedEnabled = (acc.publish_enabled == 1);
        final String domain = acc.getDefaultDomain();

        // Bind datas to view
        //tv.setText(displayName);  //Commented by Esstel Softwares
        tv.setText("Starred Android Contacts");

        icon.setImageResource(WizardUtils.getWizardIconRes(wizard));
        //  presSpinner.setProfileId(profileId);

        // Extra menu view if not already set
        ViewGroup menuViewWrapper = (ViewGroup) view.findViewById(R.id.header_cfg_spinner);

        MenuCallback newMcb = new MenuCallback(context, profileId, groupName, domain, publishedEnabled);
        MenuBuilder menuBuilder;
        if (menuViewWrapper.getTag() == null) {

            final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.MATCH_PARENT);

            ActionMenuPresenter mActionMenuPresenter = new ActionMenuPresenter(mContext);
            mActionMenuPresenter.setReserveOverflow(true);
            menuBuilder = new MenuBuilder(context);
            menuBuilder.setCallback(newMcb);
            MenuInflater inflater = new MenuInflater(context);
            inflater.inflate(R.menu.fav_menu_new, menuBuilder);
            menuBuilder.addMenuPresenter(mActionMenuPresenter);
            ActionMenuView menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(menuViewWrapper);
            UtilityWrapper.getInstance().setBackgroundDrawable(menuView, null);
            menuViewWrapper.addView(menuView, layoutParams);
            menuViewWrapper.setTag(menuBuilder);
        } else {
            menuBuilder = (MenuBuilder) menuViewWrapper.getTag();
            menuBuilder.setCallback(newMcb);
        }
        //  menuBuilder.findItem(R.id.share_presence).setTitle(publishedEnabled ? R.string.deactivate_presence_sharing : R.string.activate_presence_sharing);
        // menuBuilder.findItem(R.id.set_sip_data).setVisible(!TextUtils.isEmpty(groupName));

    } else if (type == ContactsWrapper.TYPE_CONTACT) {
        ContactInfo ci = ContactsWrapper.getInstance().getContactInfo(context, cursor);
        ci.userData = cursor.getPosition();
        // Get views
        TextView tv = (TextView) view.findViewById(R.id.contact_name);
        QuickContactBadge badge = (QuickContactBadge) view.findViewById(R.id.quick_contact_photo);
        TextView statusText = (TextView) view.findViewById(R.id.status_text);
        ImageView statusImage = (ImageView) view.findViewById(R.id.status_icon);

        // Bind
        if (ci.contactId != null) {
            tv.setText(ci.displayName);
            badge.assignContactUri(ci.callerInfo.contactContentUri);
            ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(context, badge.getImageView(),
                    ci.callerInfo, R.drawable.ic_contact_picture_holo_dark);

            statusText.setVisibility(ci.hasPresence ? View.VISIBLE : View.GONE);
            statusText.setText(ci.status);
            statusImage.setVisibility(ci.hasPresence ? View.VISIBLE : View.GONE);
            statusImage.setImageResource(ContactsWrapper.getInstance().getPresenceIconResourceId(ci.presence));
        }
        View v;
        v = view.findViewById(R.id.contact_view);
        v.setTag(ci);
        v.setOnClickListener(mPrimaryActionListener);
        v = view.findViewById(R.id.secondary_action_icon);
        v.setTag(ci);
        v.setOnClickListener(mSecondaryActionListener);
    } else if (type == ContactsWrapper.TYPE_CONFIGURE) {
        // We only bind if it's the correct type
        // View v = view.findViewById(R.id.configure_view);
        //v.setOnClickListener(this);
        //ConfigureObj cfg = new ConfigureObj();
        // cfg.profileId = cv.getAsLong(BaseColumns._ID);
        // v.setTag(cfg);
    }
}

From source file:com.tandong.sa.sherlock.widget.SearchView.java

/**
 * When a particular suggestion has been selected, perform the various
 * lookups required to use the suggestion. This includes checking the cursor
 * for suggestion-specific data, and/or falling back to the XML for
 * defaults; It also creates REST style Uri data when the suggestion
 * includes a data id.//from   www .ja  va 2  s.  c  o  m
 * 
 * @param c
 *            The suggestions cursor, moved to the row of the user's
 *            selection
 * @param actionKey
 *            The key code of the action key that was pressed, or
 *            {@link KeyEvent#KEYCODE_UNKNOWN} if none.
 * @param actionMsg
 *            The message for the action key that was pressed, or
 *            <code>null</code> if none.
 * @return An intent for the suggestion at the cursor's position.
 */
private Intent createIntentFromSuggestion(Cursor c, int actionKey, String actionMsg) {
    try {
        // use specific action if supplied, or default action if supplied,
        // or fixed default
        String action = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_ACTION);

        if (action == null) {
            action = mSearchable.getSuggestIntentAction();
        }
        if (action == null) {
            action = Intent.ACTION_SEARCH;
        }

        // use specific data if supplied, or default data if supplied
        String data = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA);
        if (data == null) {
            data = mSearchable.getSuggestIntentData();
        }
        // then, if an ID was provided, append it.
        if (data != null) {
            String id = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
            if (id != null) {
                data = data + "/" + Uri.encode(id);
            }
        }
        Uri dataUri = (data == null) ? null : Uri.parse(data);

        String query = getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY);
        String extraData = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);

        return createIntent(action, dataUri, extraData, query, actionKey, actionMsg);
    } catch (RuntimeException e) {
        int rowNum;
        try { // be really paranoid now
            rowNum = c.getPosition();
        } catch (RuntimeException e2) {
            rowNum = -1;
        }
        Log.w(LOG_TAG, "Search suggestions cursor at row " + rowNum + " returned exception.", e);
        return null;
    }
}

From source file:org.apache.cordova.ContactAccessorSdk5.java

/**
 * Creates an array of contacts from the cursor you pass in
 *
 * @param limit        max number of contacts for the array
 * @param populate     whether or not you should populate a certain value
 * @param c            the cursor//from  w  w  w  . jav  a 2s.c o  m
 * @return             a JSONArray of contacts
 */
private JSONArray populateContactArray(int limit, HashMap<String, Boolean> populate, Cursor c) {

    String contactId = "";
    String rawId = "";
    String oldContactId = "";
    boolean newContact = true;
    String mimetype = "";

    JSONArray contacts = new JSONArray();
    JSONObject contact = new JSONObject();
    JSONArray organizations = new JSONArray();
    JSONArray addresses = new JSONArray();
    JSONArray phones = new JSONArray();
    JSONArray emails = new JSONArray();
    JSONArray ims = new JSONArray();
    JSONArray websites = new JSONArray();
    JSONArray photos = new JSONArray();

    // Column indices
    int colContactId = c.getColumnIndex(ContactsContract.Data.CONTACT_ID);
    int colRawContactId = c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
    int colMimetype = c.getColumnIndex(ContactsContract.Data.MIMETYPE);
    int colDisplayName = c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
    int colNote = c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE);
    int colNickname = c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME);
    int colBirthday = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
    int colEventType = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE);

    if (c.getCount() > 0) {
        while (c.moveToNext() && (contacts.length() <= (limit - 1))) {
            try {
                contactId = c.getString(colContactId);
                rawId = c.getString(colRawContactId);

                // If we are in the first row set the oldContactId
                if (c.getPosition() == 0) {
                    oldContactId = contactId;
                }

                // When the contact ID changes we need to push the Contact object
                // to the array of contacts and create new objects.
                if (!oldContactId.equals(contactId)) {
                    // Populate the Contact object with it's arrays
                    // and push the contact into the contacts array
                    contacts.put(populateContact(contact, organizations, addresses, phones, emails, ims,
                            websites, photos));

                    // Clean up the objects
                    contact = new JSONObject();
                    organizations = new JSONArray();
                    addresses = new JSONArray();
                    phones = new JSONArray();
                    emails = new JSONArray();
                    ims = new JSONArray();
                    websites = new JSONArray();
                    photos = new JSONArray();

                    // Set newContact to true as we are starting to populate a new contact
                    newContact = true;
                }

                // When we detect a new contact set the ID and display name.
                // These fields are available in every row in the result set returned.
                if (newContact) {
                    newContact = false;
                    contact.put("id", contactId);
                    contact.put("rawId", rawId);
                }

                // Grab the mimetype of the current row as it will be used in a lot of comparisons
                mimetype = c.getString(colMimetype);

                if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) {
                    contact.put("displayName", c.getString(colDisplayName));
                }

                if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        && isRequired("name", populate)) {
                    contact.put("name", nameQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        && isRequired("phoneNumbers", populate)) {
                    phones.put(phoneQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                        && isRequired("emails", populate)) {
                    emails.put(emailQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                        && isRequired("addresses", populate)) {
                    addresses.put(addressQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                        && isRequired("organizations", populate)) {
                    organizations.put(organizationQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
                        && isRequired("ims", populate)) {
                    ims.put(imQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
                        && isRequired("note", populate)) {
                    contact.put("note", c.getString(colNote));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
                        && isRequired("nickname", populate)) {
                    contact.put("nickname", c.getString(colNickname));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
                        && isRequired("urls", populate)) {
                    websites.put(websiteQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)) {
                    if (isRequired("birthday", populate)
                            && ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c.getInt(colEventType)) {
                        contact.put("birthday", c.getString(colBirthday));
                    }
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                        && isRequired("photos", populate)) {
                    photos.put(photoQuery(c, contactId));
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }

            // Set the old contact ID
            oldContactId = contactId;

        }

        // Push the last contact into the contacts array
        if (contacts.length() < limit) {
            contacts.put(
                    populateContact(contact, organizations, addresses, phones, emails, ims, websites, photos));
        }
    }
    c.close();
    return contacts;
}