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.jefftharris.passwdsafe.sync.SyncLogsFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    itsLogsAdapter = new SimpleCursorAdapter(getActivity(), R.layout.listview_sync_log_item, null,
            new String[] { PasswdSafeContract.SyncLogs.COL_START, PasswdSafeContract.SyncLogs.COL_LOG,
                    PasswdSafeContract.SyncLogs.COL_STACK },
            new int[] { R.id.title, R.id.log, R.id.stack }, 0);

    itsLogsAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        @Override//  ww  w  .j ava  2 s . co  m
        public boolean setViewValue(View view, Cursor cursor, int colIdx) {
            switch (colIdx) {
            case PasswdSafeContract.SyncLogs.PROJECTION_IDX_START: {
                long start = cursor.getLong(PasswdSafeContract.SyncLogs.PROJECTION_IDX_START);
                long end = cursor.getLong(PasswdSafeContract.SyncLogs.PROJECTION_IDX_END);
                String acct = cursor.getString(PasswdSafeContract.SyncLogs.PROJECTION_IDX_ACCT);
                TextView tv = (TextView) view;

                String str = String.format(Locale.US, "%s (%ds) - %s", Utils.formatDate(start, getActivity()),
                        (end - start) / 1000, acct);
                tv.setText(str);
                return true;
            }
            case PasswdSafeContract.SyncLogs.PROJECTION_IDX_LOG: {
                int flags = cursor.getInt(PasswdSafeContract.SyncLogs.PROJECTION_IDX_FLAGS);
                String log = cursor.getString(PasswdSafeContract.SyncLogs.PROJECTION_IDX_LOG);

                StringBuilder str = new StringBuilder();
                if ((flags & PasswdSafeContract.SyncLogs.FLAGS_IS_MANUAL) != 0) {
                    str.append(getString(R.string.manual));
                } else {
                    str.append(getString(R.string.automatic));
                }

                str.append(", ");
                if ((flags & PasswdSafeContract.SyncLogs.FLAGS_IS_NOT_CONNECTED) != 0) {
                    str.append(getString(R.string.network_not_connected));
                } else {
                    str.append(getString(R.string.network_connected));
                }

                if (log.length() != 0) {
                    str.append("\n");
                }
                str.append(log);
                TextView tv = (TextView) view;
                tv.setText(str.toString());
                return true;
            }
            case PasswdSafeContract.SyncLogs.PROJECTION_IDX_STACK: {
                boolean checked = getListView().isItemChecked(cursor.getPosition());
                String stack;
                if (checked) {
                    stack = cursor.getString(PasswdSafeContract.SyncLogs.PROJECTION_IDX_STACK);
                } else {
                    stack = null;
                }

                GuiUtils.setVisible(view, checked && !TextUtils.isEmpty(stack));
                ((TextView) view).setText(stack);
                return true;
            }
            }
            return false;
        }
    });

    setListAdapter(itsLogsAdapter);
    setEmptyText(getString(R.string.no_logs));
    getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    itsLogsCbs = new LoaderCallbacks<Cursor>() {
        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            String selection = itsIsShowAll ? null : PasswdSafeContract.SyncLogs.DEFAULT_SELECTION;
            return new PasswdCursorLoader(getActivity(), PasswdSafeContract.SyncLogs.CONTENT_URI,
                    PasswdSafeContract.SyncLogs.PROJECTION, selection, null,
                    PasswdSafeContract.SyncLogs.START_SORT_ORDER);
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
            if (PasswdCursorLoader.checkResult(loader)) {
                itsLogsAdapter.swapCursor(cursor);
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
            if (PasswdCursorLoader.checkResult(loader)) {
                itsLogsAdapter.swapCursor(null);
            }
        }
    };
    LoaderManager lm = getLoaderManager();
    lm.initLoader(LOADER_LOGS, null, itsLogsCbs);
}

From source file:org.servalproject.maps.export.CsvAsyncTask.java

private Integer doLocationExport() {

    if (V_LOG) {//from w w  w  .  j  a  va  2 s  .c  om
        Log.v(TAG, "doLocationExport called: ");
    }

    // reset the progress bar
    progressBar.setProgress(0);
    Integer mRecordCount = 0;

    updateUI = true;
    updateForLocation = true;

    // get all of the location data
    ContentResolver mContentResolver = context.getApplicationContext().getContentResolver();

    // get the content
    Cursor mCursor = mContentResolver.query(LocationsContract.CONTENT_URI, null, null, null, null);

    // check on what was returned
    if (mCursor.getCount() > 0) {

        progressBar.setMax(mCursor.getCount());
        mRecordCount = mCursor.getCount();

        // get the export directory 
        // get the path for the output files
        String mOutputPath = Environment.getExternalStorageDirectory().getPath();
        mOutputPath += context.getString(R.string.system_path_export_data);

        if (FileUtils.isDirectoryWritable(mOutputPath) == false) {
            Log.e(TAG, "unable to access the required output directory");
            mCursor.close();
            return 0;
        }

        // build the output file name
        String mFileName = "serval-maps-export-locations-" + TimeUtils.getToday() + ".csv";

        // write the data to the file
        BufferedWriter mOutput = null;

        String[] mLine = new String[LocationsContract.Table.COLUMNS.length];

        try {
            //mOutput = new BufferedOutputStream(new FileOutputStream(mOutputPath + mFileName, false));
            mOutput = new BufferedWriter(new FileWriter(mOutputPath + mFileName, false));

            CSVPrinter mPrinter = new CSVPrinter(mOutput, csvFormat);

            // write the comment line
            mPrinter.printComment("Location data sourced from the Serval Maps application");
            mPrinter.printComment("File created: " + TimeUtils.getToday());
            mPrinter.printComment(Arrays.toString(LocationsContract.Table.COLUMNS));

            while (mCursor.moveToNext()) {

                for (int i = 0; i < LocationsContract.Table.COLUMNS.length; i++) {
                    mLine[i] = mCursor.getString(mCursor.getColumnIndex(LocationsContract.Table.COLUMNS[i]));
                }

                mPrinter.println(mLine);

                publishProgress(mCursor.getPosition());

                // check to see if we need to cancel this task
                if (isCancelled() == true) {
                    break;
                }
            }

        } catch (FileNotFoundException e) {
            Log.e(TAG, "unable to open the output file", e);
        } catch (IOException e) {
            Log.e(TAG, "unable to write the message at '" + mCursor.getPosition() + "' in the cursor", e);
        } finally {
            // play nice and tidy up
            try {
                if (mOutput != null) {
                    mOutput.close();
                }
            } catch (IOException e) {
                Log.e(TAG, "unable to close the output file", e);
            }
            mCursor.close();
        }
    }

    return mRecordCount;
}

From source file:org.servalproject.maps.export.CsvAsyncTask.java

private Integer doPoiExport() {

    // reset the progress bar
    progressBar.setProgress(0);//from   www  .ja v a2  s.c om
    Integer mRecordCount = 0;

    updateUI = true;
    updateForPoi = true;

    if (V_LOG) {
        Log.v(TAG, "doPoiExport called: ");
    }

    // get all of the location data
    ContentResolver mContentResolver = context.getApplicationContext().getContentResolver();

    // get the content
    Cursor mCursor = mContentResolver.query(PointsOfInterestContract.CONTENT_URI, null, null, null, null);

    // check on what was returned
    if (mCursor.getCount() > 0) {

        progressBar.setMax(mCursor.getCount());
        mRecordCount = mCursor.getCount();

        // get the export directory 
        // get the path for the output files
        String mOutputPath = Environment.getExternalStorageDirectory().getPath();
        mOutputPath += context.getString(R.string.system_path_export_data);

        if (FileUtils.isDirectoryWritable(mOutputPath) == false) {
            Log.e(TAG, "unable to access the required output directory");
            mCursor.close();
            return 0;
        }

        // build the output file name
        String mFileName = "serval-maps-export-pois-" + TimeUtils.getToday() + ".csv";

        // write the data to the file
        BufferedWriter mOutput = null;

        String[] mLine = new String[PointsOfInterestContract.Table.COLUMNS.length];

        try {
            //mOutput = new BufferedOutputStream(new FileOutputStream(mOutputPath + mFileName, false));
            mOutput = new BufferedWriter(new FileWriter(mOutputPath + mFileName, false));

            CSVPrinter mPrinter = new CSVPrinter(mOutput, csvFormat);

            // write the comment line
            mPrinter.printComment("Location data sourced from the Serval Maps application");
            mPrinter.printComment("File created: " + TimeUtils.getToday());
            mPrinter.printComment(Arrays.toString(PointsOfInterestContract.Table.COLUMNS));

            while (mCursor.moveToNext()) {

                for (int i = 0; i < PointsOfInterestContract.Table.COLUMNS.length; i++) {
                    mLine[i] = mCursor
                            .getString(mCursor.getColumnIndex(PointsOfInterestContract.Table.COLUMNS[i]));
                }

                mPrinter.println(mLine);

                publishProgress(mCursor.getPosition());

                // check to see if we need to cancel this task
                if (isCancelled() == true) {
                    break;
                }
            }

        } catch (FileNotFoundException e) {
            Log.e(TAG, "unable to open the output file", e);
        } catch (IOException e) {
            Log.e(TAG, "unable to write the message at '" + mCursor.getPosition() + "' in the cursor", e);
        } finally {
            // play nice and tidy up
            try {
                if (mOutput != null) {
                    mOutput.close();
                }
            } catch (IOException e) {
                Log.e(TAG, "unable to close the output file", e);
            }
            mCursor.close();
        }
    }

    return mRecordCount;
}

From source file:org.sufficientlysecure.keychain.ui.adapter.MultiUserIdsAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView vHeaderId = (TextView) view.findViewById(R.id.user_id_header);
    TextView vName = (TextView) view.findViewById(R.id.user_id_item_name);
    TextView vAddresses = (TextView) view.findViewById(R.id.user_id_item_addresses);

    byte[] data = cursor.getBlob(1);
    int isHeader = cursor.getInt(2);
    Parcel p = Parcel.obtain();/*from ww w.  j  a  v  a2  s  .  c  om*/
    p.unmarshall(data, 0, data.length);
    p.setDataPosition(0);
    ArrayList<String> uids = p.createStringArrayList();
    p.recycle();

    { // first one
        String userId = uids.get(0);
        OpenPgpUtils.UserId splitUserId = KeyRing.splitUserId(userId);
        if (splitUserId.name != null) {
            vName.setText(splitUserId.name);
        } else {
            vName.setText(R.string.user_id_no_name);
        }

        if (isHeader == 1) {
            vHeaderId.setVisibility(View.VISIBLE);
            String message;
            if (splitUserId.name != null) {
                message = mContext.getString(R.string.section_uids_to_certify) + splitUserId.name;
            } else {
                message = mContext.getString(R.string.section_uids_to_certify)
                        + context.getString(R.string.user_id_no_name);
            }
            vHeaderId.setText(message);
        } else {
            vHeaderId.setVisibility(View.GONE);
        }
    }

    StringBuilder lines = new StringBuilder();
    for (String uid : uids) {
        OpenPgpUtils.UserId splitUserId = KeyRing.splitUserId(uid);
        if (splitUserId.email == null) {
            continue;
        }
        lines.append(splitUserId.email);
        if (splitUserId.comment != null) {
            lines.append(" (").append(splitUserId.comment).append(")");
        }
        lines.append('\n');
    }

    // If we have any data here, show it
    if (lines.length() > 0) {
        // delete last newline
        lines.setLength(lines.length() - 1);
        vAddresses.setVisibility(View.VISIBLE);
        vAddresses.setText(lines);
    } else {
        vAddresses.setVisibility(View.GONE);
    }

    final CheckBox vCheckBox = (CheckBox) view.findViewById(R.id.user_id_item_check_box);
    final int position = cursor.getPosition();
    vCheckBox.setOnCheckedChangeListener(null);
    vCheckBox.setChecked(mCheckStates.get(position));
    vCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            mCheckStates.set(position, b);
        }
    });
    vCheckBox.setClickable(false);
    vCheckBox.setVisibility(checkboxVisibility ? View.VISIBLE : View.GONE);

    View vUidBody = view.findViewById(R.id.user_id_body);
    vUidBody.setClickable(true);
    vUidBody.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            vCheckBox.toggle();
        }
    });

}

From source file:org.sufficientlysecure.keychain.ui.adapter.ViewKeyUserIdsAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    TextView vName = (TextView) view.findViewById(R.id.userId);
    TextView vAddress = (TextView) view.findViewById(R.id.address);
    TextView vComment = (TextView) view.findViewById(R.id.comment);
    ImageView vVerified = (ImageView) view.findViewById(R.id.certified);

    String[] userId = PgpKeyHelper.splitUserId(cursor.getString(mIndexUserId));
    if (userId[0] != null) {
        vName.setText(userId[0]);//w w  w.j av a  2 s.  c  o  m
    } else {
        vName.setText(R.string.user_id_no_name);
    }
    if (userId[1] != null) {
        vAddress.setText(userId[1]);
        vAddress.setVisibility(View.VISIBLE);
    } else {
        vAddress.setVisibility(View.GONE);
    }
    if (userId[2] != null) {
        vComment.setText(userId[2]);
        vComment.setVisibility(View.VISIBLE);
    } else {
        vComment.setVisibility(View.GONE);
    }

    // show small star icon for primary user ids
    boolean isPrimary = cursor.getInt(mIsPrimary) != 0;

    if (cursor.getInt(mIsRevoked) > 0) {

        // set revocation icon (can this even be primary?)
        vVerified.setImageResource(R.drawable.key_certify_revoke);

        // disable and strike through text for revoked user ids
        vName.setEnabled(false);
        vAddress.setEnabled(false);
        vName.setText(OtherHelper.strikeOutText(vName.getText()));
        vAddress.setText(OtherHelper.strikeOutText(vAddress.getText()));
    } else {
        vName.setEnabled(true);
        vAddress.setEnabled(true);

        int verified = cursor.getInt(mVerifiedId);
        switch (verified) {
        case Certs.VERIFIED_SECRET:
            vVerified.setImageResource(
                    isPrimary ? R.drawable.key_certify_primary_ok_depth0 : R.drawable.key_certify_ok_depth0);
            break;
        case Certs.VERIFIED_SELF:
            vVerified.setImageResource(
                    isPrimary ? R.drawable.key_certify_primary_ok_self : R.drawable.key_certify_ok_self);
            break;
        default:
            vVerified.setImageResource(R.drawable.key_certify_error);
            break;
        }
    }

    // don't care further if checkboxes aren't shown
    if (mCheckStates == null) {
        return;
    }

    final CheckBox vCheckBox = (CheckBox) view.findViewById(R.id.checkBox);
    final int position = cursor.getPosition();
    vCheckBox.setOnCheckedChangeListener(null);
    vCheckBox.setChecked(mCheckStates.get(position));
    vCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            mCheckStates.set(position, b);
        }
    });
    vCheckBox.setClickable(false);

}

From source file:com.mycompany.popularmovies.DetailActivity.DetailFragment.java

@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
    if (cursorLoader == mGeneralInfoLoader) {
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndexPosterPath = cursor.getColumnIndex(MovieContract.MovieTable.COLUMN_POSTER_PATH);
            String posterPath = MovieAdapter.POSTER_BASE_URL_W185 + cursor.getString(columnIndexPosterPath);
            Picasso picasso = Picasso.with(getActivity());
            picasso.load(posterPath).into(mPosterImageView);

            int columnIndexTitle = cursor.getColumnIndex(MovieContract.MovieTable.COLUMN_TITLE);
            String title = cursor.getString(columnIndexTitle);
            mTitleTextView.setText(title);

            int columnIndexIsFavorite = cursor.getColumnIndex(MovieContract.MovieTable.COLUMN_FAVORITED);
            int isFavorite = cursor.getInt(columnIndexIsFavorite);
            mHeartImageView//from www. ja v a  2  s  .co m
                    .setImageResource(isFavorite == 1 ? R.drawable.heart_active : R.drawable.heart_inactive);
            mHeartImageView.setOnClickListener(this);

            int columnIndexReleaseDate = cursor.getColumnIndex(MovieContract.MovieTable.COLUMN_RELEASE_DATE);
            String releaseDateText = cursor.getString(columnIndexReleaseDate);
            String releaseYearText = releaseDateText.substring(0, Math.min(releaseDateText.length(), 4));
            mReleaseYearTextView.setText(releaseYearText);

            int columnIndexVoteAverage = cursor.getColumnIndex(MovieContract.MovieTable.COLUMN_VOTE_AVERAGE);
            float vote_average = cursor.getFloat(columnIndexVoteAverage);
            mRatingBar.setRating(vote_average);

            int columnIndexSynopsis = cursor.getColumnIndex(MovieContract.MovieTable.COLUMN_SYNOPSIS);
            mSynopsisTextView.setText(cursor.getString(columnIndexSynopsis));

            // If onCreateOptionsMenu has already happened, we need to update the share intent now.
            if (mShareActionProvider != null) {
                mShareText = title;
                mShareActionProvider.setShareIntent(createShareIntent());
            }
        } else {
            Log.e(LOG_TAG, "Cursor to populate general info was empty or null!");
        }
    } else if (cursorLoader == mTrailerLoader) {
        if (cursor == null || !cursor.moveToFirst()) {
            mTrailerListTitle.setVisibility(View.INVISIBLE);
        } else {
            mTrailerListTitle.setVisibility(View.VISIBLE);
            for (cursor.moveToFirst(); cursor.getPosition() < cursor.getCount(); cursor.moveToNext()) {
                int columnIndexName = cursor.getColumnIndex(MovieContract.TrailersTable.COLUMN_NAME);
                String trailerName = cursor.getString(columnIndexName);

                int columnIndexLanguageCode = cursor
                        .getColumnIndex(MovieContract.TrailersTable.COLUMN_LANGUAGE_CODE);
                String trailerLanguageCode = cursor.getString(columnIndexLanguageCode);

                String trailer_summary = String.format("%s (%s)", trailerName,
                        trailerLanguageCode.toUpperCase());

                int columnIndexSite = cursor.getColumnIndex(MovieContract.TrailersTable.COLUMN_SITE);
                String site = cursor.getString(columnIndexSite);

                int columnIndexKey = cursor.getColumnIndex(MovieContract.TrailersTable.COLUMN_KEY);
                String key = cursor.getString(columnIndexKey);

                String link = null;
                if (site.compareTo("YouTube") == 0) {
                    link = "https://www.youtube.com/watch?v=" + key;
                } else {
                    Log.e(LOG_TAG, "Unsupported site: " + site);
                }

                ImageView trailerThumbnail = (ImageView) mActivity.getLayoutInflater()
                        .inflate(R.layout.detail_fragment_trailer_item, null, false);
                if (site.compareTo("YouTube") == 0) {
                    Picasso picasso = Picasso.with(mActivity);
                    String youtubeThumbnailPath = String.format("http://img.youtube.com/vi/%s/mqdefault.jpg",
                            key);
                    picasso.load(youtubeThumbnailPath).into(trailerThumbnail);
                    trailerThumbnail.setTag(link);
                    trailerThumbnail.setOnClickListener(this);
                }

                mTrailerList.addView(trailerThumbnail);
            }
        }
    } else if (cursorLoader == mReviewLoader) {
        if (cursor == null || !cursor.moveToFirst()) {
            mReviewListTitle.setVisibility(View.INVISIBLE);
        } else {
            mReviewListTitle.setVisibility(View.VISIBLE);
            String colors[] = { "#00BFFF", "#00CED1", "#FF8C00", "#00FA9A", "#9400D3" };
            for (cursor.moveToFirst(); cursor.getPosition() < cursor.getCount(); cursor.moveToNext()) {
                int columnIndexAuthor = cursor.getColumnIndex(MovieContract.ReviewsTable.COLUMN_AUTHOR);
                String author = cursor.getString(columnIndexAuthor);
                String authorAbbreviation = author != null && author.length() >= 1 ? author.substring(0, 1)
                        : "?";

                int columnIndexReviewText = cursor
                        .getColumnIndex(MovieContract.ReviewsTable.COLUMN_REVIEW_TEXT);
                String reviewText = cursor.getString(columnIndexReviewText);

                RelativeLayout review = (RelativeLayout) mActivity.getLayoutInflater()
                        .inflate(R.layout.detail_fragment_review_item, null, false);
                review.setOnClickListener(this);
                review.setTag(TAG_REVIEW_COLLAPSED);

                TextView authorIcon = (TextView) review.findViewById(R.id.author_icon);
                authorIcon.setText(authorAbbreviation);
                int color = Color.parseColor(colors[cursor.getPosition() % colors.length]);
                authorIcon.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);

                TextView authorFullName = (TextView) review.findViewById(R.id.author_full_name);
                authorFullName.setText(author);

                TextView reviewTextView = (TextView) review.findViewById(R.id.review_text);
                reviewTextView.setText(reviewText);

                mReviewList.addView(review);
            }
        }
    }
}

From source file:com.phonegap.ContactAccessorSdk5.java

/** 
 * This method takes the fields required and search options in order to produce an 
 * array of contacts that matches the criteria provided.
 * @param fields an array of items to be used as search criteria
 * @param options that can be applied to contact searching
 * @return an array of contacts /*  w  ww  .jav a 2  s  .  c o m*/
 */
@Override
public JSONArray search(JSONArray fields, JSONObject options) {
    long totalEnd;
    long totalStart = System.currentTimeMillis();

    // Get the find options
    String searchTerm = "";
    int limit = Integer.MAX_VALUE;
    boolean multiple = true;

    if (options != null) {
        searchTerm = options.optString("filter");
        if (searchTerm.length() == 0) {
            searchTerm = "%";
        } else {
            searchTerm = "%" + searchTerm + "%";
        }
        try {
            multiple = options.getBoolean("multiple");
            if (!multiple) {
                limit = 1;
            }
        } catch (JSONException e) {
            // Multiple was not specified so we assume the default is true.
        }
    } else {
        searchTerm = "%";
    }

    //Log.d(LOG_TAG, "Search Term = " + searchTerm);
    //Log.d(LOG_TAG, "Field Length = " + fields.length());
    //Log.d(LOG_TAG, "Fields = " + fields.toString());

    // Loop through the fields the user provided to see what data should be returned.
    HashMap<String, Boolean> populate = buildPopulationSet(fields);

    // Build the ugly where clause and where arguments for one big query.
    WhereOptions whereOptions = buildWhereClause(fields, searchTerm);

    // Get all the id's where the search term matches the fields passed in.
    Cursor idCursor = mApp.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
            new String[] { ContactsContract.Data.CONTACT_ID }, whereOptions.getWhere(),
            whereOptions.getWhereArgs(), ContactsContract.Data.CONTACT_ID + " ASC");

    // Create a set of unique ids
    //Log.d(LOG_TAG, "ID cursor query returns = " + idCursor.getCount());
    Set<String> contactIds = new HashSet<String>();
    while (idCursor.moveToNext()) {
        contactIds.add(idCursor.getString(idCursor.getColumnIndex(ContactsContract.Data.CONTACT_ID)));
    }
    idCursor.close();

    // Build a query that only looks at ids
    WhereOptions idOptions = buildIdClause(contactIds, searchTerm);

    // Do the id query
    Cursor c = mApp.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, idOptions.getWhere(),
            idOptions.getWhereArgs(), ContactsContract.Data.CONTACT_ID + " ASC");

    //Log.d(LOG_TAG, "Cursor length = " + c.getCount());

    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();

    if (c.getCount() > 0) {
        while (c.moveToNext() && (contacts.length() <= (limit - 1))) {
            try {
                contactId = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
                rawId = c.getString(c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));

                // 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("displayName", c.getString(
                            c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME)));
                }

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

                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(c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE)));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
                        && isRequired("nickname", populate)) {
                    contact.put("nickname",
                            c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME)));
                } 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 (ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c
                            .getInt(c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE))
                            && isRequired("birthday", populate)) {
                        contact.put("birthday", c.getString(
                                c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE)));
                    }
                } 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();

    totalEnd = System.currentTimeMillis();
    Log.d(LOG_TAG, "Total time = " + (totalEnd - totalStart));
    return contacts;
}

From source file:org.skt.runtime.html5apis.contacts.ContactAccessorSdk5.java

/** 
 * Creates an array of contacts from the cursor you pass in
 * /*  w w  w.ja  va 2s .  c  o  m*/
 * @param limit        max number of contacts for the array
 * @param populate     whether or not you should populate a certain value
 * @param c            the cursor
 * @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();

    if (c.getCount() > 0) {
        while (c.moveToNext() && (contacts.length() <= (limit - 1))) {
            try {
                contactId = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
                rawId = c.getString(c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));

                // 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(c.getColumnIndex(ContactsContract.Data.MIMETYPE));

                if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) {
                    contact.put("displayName", c.getString(
                            c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME)));
                }
                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(c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE)));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
                        && isRequired("nickname", populate)) {
                    contact.put("nickname",
                            c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME)));
                } 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 (ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c
                            .getInt(c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE))
                            && isRequired("birthday", populate)) {
                        contact.put("birthday", c.getString(
                                c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE)));
                    }
                } 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;
}

From source file:cm.aptoide.com.actionbarsherlock.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 w ww .  ja  va 2 s.co  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:android.support.v7.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  w w w  .ja  v  a 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 && 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;
    }
}