Example usage for android.database Cursor moveToPosition

List of usage examples for android.database Cursor moveToPosition

Introduction

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

Prototype

boolean moveToPosition(int position);

Source Link

Document

Move the cursor to an absolute position.

Usage

From source file:com.ktouch.kdc.launcher4.camera.ui.ReviewDrawer.java

/**
 * Clears the list of images and reload it from the Gallery (MediaStore)
 * This method is synchronous, see updateFromGallery for the threaded one.
 *
 * @param images True to get images, false to get videos
 * @param scrollPos Position to scroll to, or 0 to get latest image
 *//*from  w ww . j  a va2s . co  m*/
public void updateFromGallerySynchronous(final boolean images, final int scrollPos) {
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            synchronized (mImagesLock) {
                mImages.clear();
                mImagesListAdapter.notifyDataSetChanged();
            }

            String[] columns;
            String orderBy;
            if (images) {
                columns = new String[] { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
                orderBy = MediaStore.Images.Media.DATE_TAKEN + " ASC";
            } else {
                columns = new String[] { MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID };
                orderBy = MediaStore.Video.Media.DATE_TAKEN + " ASC";
            }

            // Select only the images that has been taken from the Camera
            Context ctx = getContext();
            if (ctx == null)
                return;
            ContentResolver cr = ctx.getContentResolver();
            if (cr == null) {
                Log.e(TAG, "No content resolver!");
                return;
            }

            Cursor cursor;

            if (images) {
                cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
                        MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " LIKE ?",
                        new String[] { GALLERY_CAMERA_BUCKET }, orderBy);
            } else {
                cursor = cr.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns,
                        MediaStore.Video.Media.BUCKET_DISPLAY_NAME + " LIKE ?",
                        new String[] { GALLERY_CAMERA_BUCKET }, orderBy);
            }

            if (cursor == null) {
                Log.e(TAG, "Null cursor from MediaStore!");
                return;
            }

            final int imageColumnIndex = cursor
                    .getColumnIndex(images ? MediaStore.Images.Media._ID : MediaStore.Video.Media._ID);

            for (int i = 0; i < cursor.getCount(); i++) {
                cursor.moveToPosition(i);

                int id = cursor.getInt(imageColumnIndex);
                if (mReviewedImageId <= 0) {
                    mReviewedImageId = id;
                }
                addImageToList(id);
                mImagesListAdapter.notifyDataSetChanged();
            }

            cursor.close();

            if (scrollPos < mImages.size()) {
                mViewPager.setCurrentItem(scrollPos + 1, false);
                mViewPager.setCurrentItem(scrollPos, true);
            }
        }
    });
}

From source file:com.silentcircle.contacts.calllognew.CallLogAdapter.java

/**
 * Returns the call types for the given number of items in the cursor.
 * <p>/* ww w .jav  a  2  s . co m*/
 * It uses the next {@code count} rows in the cursor to extract the types.
 * <p>
 * It position in the cursor is unchanged by this function.
 */
private int[] getCallTypes(Cursor cursor, int count) {
    int position = cursor.getPosition();
    int[] callTypes = new int[count];
    for (int index = 0; index < count; ++index) {
        callTypes[index] = cursor.getInt(CallLogQuery.CALL_TYPE);
        cursor.moveToNext();
    }
    cursor.moveToPosition(position);
    return callTypes;
}

From source file:com.weebly.opus1269.copyeverywhere.ui.main.MainActivity.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // Swap the new cursor in.  (The framework will take care of closing the
    // old cursor once we return.)
    mAdapter.swapCursor(data);/*www.jav a 2s. c  om*/

    if (data == null) {
        return;
    }

    if (AppUtils.isDualPane()) {
        // Update the selected item and ClipViewer text.
        // Can't create a new fragment here.
        // see: http://goo.gl/IFQkPc
        if (data.getCount() == 0) {
            setSelectedItemID(-1L);
            showClipViewer(new ClipItem());
        } else {
            int pos;
            if (mSelectedItemID == -1L) {
                pos = mSelectedPos;
            } else {
                pos = mAdapter.getPosFromItemID(mSelectedItemID);
            }
            pos = Math.max(0, pos);
            data.moveToPosition(pos);
            final int index = data.getColumnIndex(ClipContract.Clip._ID);
            setSelectedItemID(data.getLong(index));
            showClipViewer(new ClipItem(data));
        }
    }
}

From source file:com.dsdar.thosearoundme.util.ContactsListFragment.java

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    // Gets the Cursor object currently bound to the ListView
    final Cursor cursor = mAdapter.getCursor();
    Contact aContactToBeRemoved = null;/*from  w w  w  .  j ava  2  s.com*/
    String aContactCursorId;
    String aEmailId = null;
    String aPhoneNumber = null;
    boolean isExist = false;
    // Moves to the Cursor row corresponding to the ListView item that was
    // clicked
    cursor.moveToPosition(position);

    // Creates a contact lookup Uri from contact ID and lookup_key
    final Uri uri = Contacts.getLookupUri(cursor.getLong(ContactsQuery.ID),
            cursor.getString(ContactsQuery.LOOKUP_KEY));

    // Notifies the parent activity that the user selected a contact. In a
    // two-pane layout, the
    // parent activity loads a ContactDetailFragment that displays the
    // details for the selected
    // contact. In a single-pane layout, the parent activity starts a new
    // activity that
    // displays contact details in its own Fragment.
    // niaz checking
    Log.d("positionI", String.valueOf(position));
    CheckedTextView aCheckedTV = (CheckedTextView) v.findViewById(android.R.id.text1);
    mOnContactSelectedListener.onContactSelected(uri);
    HashMap<Integer, Boolean> aHashMap = new HashMap<Integer, Boolean>();
    aHashMap.put(position, true);
    final Uri aContactUri = Contacts.getLookupUri(cursor.getLong(ContactsQuery.ID),
            cursor.getString(ContactsQuery.LOOKUP_KEY));

    String aName = cursor.getString(ContactsQuery.DISPLAY_NAME);
    Cursor aContactCursor = itsContext.getContentResolver().query(aContactUri, null, null, null, null);
    if (aContactCursor.moveToFirst()) {
        int idx = cursor.getColumnIndex(ContactsContract.Contacts._ID);
        aContactCursorId = cursor.getString(idx);
        int aNameIdx = aContactCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
        //
        // aEmailId = cursor.getString(ContactsQuery.LOOKUP_KEY);
        // aPhoneNumber = cursor.getString(ContactsQuery.ID);

        Cursor aPhoneNumberCursor = itsContext.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + aContactCursorId, null, null);
        if (aPhoneNumberCursor.moveToFirst()) {
            int colIdx = aPhoneNumberCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            aPhoneNumber = aPhoneNumberCursor.getString(colIdx);
        }
        aPhoneNumberCursor.close();

        if (aPhoneNumber == null || aPhoneNumber.equals("")) {
            Toast.makeText(itsContext,
                    "Contact Not Addded! The Contact you selected does not have a Phone Number",
                    Toast.LENGTH_LONG).show();

        }

        Cursor aEmailIdCursor = itsContext.getContentResolver().query(
                ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + aContactCursorId, null, null);
        if (aEmailIdCursor.moveToFirst()) {
            int colIdx = aEmailIdCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS);
            aEmailId = aEmailIdCursor.getString(colIdx);
        }
        aEmailIdCursor.close();

        Log.i("Phone&Email", aPhoneNumber + aEmailId);
        JSONObject aContactJSONObject;

        // Notifies the parent activity that the user selected a contact. In
        // a two-pane layout, the
        // parent activity loads a ContactDetailFragment that displays the
        // details for the selected
        // contact. In a single-pane layout, the parent activity starts a
        // new activity that
        // displays contact details in its own Fragment.

        if (checkedTvStates.contains(aHashMap)) {
            checkedTvStates.remove(aHashMap);
            aContactToBeRemoved = new Contact();
            aContactToBeRemoved.setEmail(aEmailId);
            aContactToBeRemoved.setName(aName);
            aContactToBeRemoved.setPhoneNumber(aPhoneNumber);
            aCheckedTV.setChecked(false);
        } else {
            checkedTvStates.add(aHashMap);
            aCheckedTV.setChecked(true);
            Contact aContact = new Contact();
            aContact.setName(aName);
            aContact.setEmail(aEmailId);
            aContact.setPhoneNumber(aPhoneNumber);

            itsContactsList.add(aContact);
        }

        if (aContactToBeRemoved != null) {
            itsContactsList.remove(aContactToBeRemoved);
        }
        // aCheckBox.setButtonDrawable(R.drawable.checkbox_notify);

        try {
            aContactJSONObject = new JSONObject();
            aMembersArray = new JSONArray();
            for (int index = 0; index < itsContactsList.size(); index++) {
                aContactJSONObject = new JSONObject();

                aContactJSONObject.put("emailId", itsContactsList.get(index).getEmail());
                aContactJSONObject.put("phone", itsContactsList.get(index).getPhoneNumber());
                aContactJSONObject.put("name", itsContactsList.get(index).getName());
                aMembersArray.put(aContactJSONObject);

            }
        } catch (JSONException e) {

            Log.e("JsonException", "Json Exception occured ", e);
        } catch (Exception e) {

            Log.e("Exception", "Exception occured ", e);
        }

    }
    // If two-pane layout sets the selected item to checked so it remains
    // highlighted. In a
    // single-pane layout a new activity is started so this is not needed.
    if (mIsTwoPaneLayout) {
        getListView().setItemChecked(position, true);
    }
}

From source file:com.google.samples.apps.iosched.ui.CurrentSessionActivity.java

private void onSpeakersQueryComplete(Cursor cursor) {
    mSpeakersCursor = true;/*w  w w.  ja  v  a 2  s . c om*/
    final ViewGroup speakersGroup = (ViewGroup) findViewById(R.id.session_speakers_block);

    // Remove all existing speakers (everything but first child, which is the header)
    for (int i = speakersGroup.getChildCount() - 1; i >= 1; i--) {
        speakersGroup.removeViewAt(i);
    }

    final LayoutInflater inflater = getLayoutInflater();

    boolean hasSpeakers = false;

    cursor.moveToPosition(-1); // move to just before first record
    while (cursor.moveToNext()) {
        final String speakerName = cursor.getString(SpeakersQuery.SPEAKER_NAME);
        if (TextUtils.isEmpty(speakerName)) {
            continue;
        }

        final String speakerImageUrl = cursor.getString(SpeakersQuery.SPEAKER_IMAGE_URL);
        final String speakerCompany = cursor.getString(SpeakersQuery.SPEAKER_COMPANY);
        final String speakerUrl = cursor.getString(SpeakersQuery.SPEAKER_URL);
        final String speakerAbstract = cursor.getString(SpeakersQuery.SPEAKER_ABSTRACT);

        String speakerHeader = speakerName;
        if (!TextUtils.isEmpty(speakerCompany)) {
            speakerHeader += ", " + speakerCompany;
        }

        final View speakerView = inflater.inflate(R.layout.speaker_detail, speakersGroup, false);
        final TextView speakerHeaderView = (TextView) speakerView.findViewById(R.id.speaker_header);
        final ImageView speakerImageView = (ImageView) speakerView.findViewById(R.id.speaker_image);
        final TextView speakerAbstractView = (TextView) speakerView.findViewById(R.id.speaker_abstract);

        if (!TextUtils.isEmpty(speakerImageUrl) && mSpeakersImageLoader != null) {
            mSpeakersImageLoader.loadImage(speakerImageUrl, speakerImageView);
        }

        speakerHeaderView.setText(speakerHeader);
        speakerImageView.setContentDescription(getString(R.string.speaker_googleplus_profile, speakerHeader));
        UIUtils.setTextMaybeHtml(speakerAbstractView, speakerAbstract);

        if (!TextUtils.isEmpty(speakerUrl)) {
            speakerImageView.setEnabled(true);
            speakerImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent speakerProfileIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(speakerUrl));
                    speakerProfileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                    UIUtils.preferPackageForIntent(CurrentSessionActivity.this, speakerProfileIntent,
                            UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
                    startActivity(speakerProfileIntent);
                }
            });
        } else {
            speakerImageView.setEnabled(false);
            speakerImageView.setOnClickListener(null);
        }

        speakersGroup.addView(speakerView);
        hasSpeakers = true;
        mHasSummaryContent = true;
    }

    speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE);
    updateEmptyView();
}

From source file:com.josenaves.sunshine.app.ForecastFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // The SimpleCursorAdapter will take data from the database through the
    // Loader and use it to populate the ListView it's attached to.
    mForecastAdapter = new SimpleCursorAdapter(getActivity(), R.layout.list_item_forecast, null,
            // the column names to use to fill the textviews
            new String[] { WeatherContract.WeatherEntry.COLUMN_DATETEXT,
                    WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
                    WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
                    WeatherContract.WeatherEntry.COLUMN_MIN_TEMP },
            // the textviews to fill with the data pulled from the columns above
            new int[] { R.id.list_item_date_textview, R.id.list_item_forecast_textview,
                    R.id.list_item_high_textview, R.id.list_item_low_textview },
            0);/*from w w w  .jav  a2  s  . co  m*/

    mForecastAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            boolean isMetric = Utility.isMetric(getActivity());
            switch (columnIndex) {
            case COL_WEATHER_MAX_TEMP:
            case COL_WEATHER_MIN_TEMP: {
                // we have to do some formatting and possibly a conversion
                ((TextView) view).setText(Utility.formatTemperature(cursor.getDouble(columnIndex), isMetric));
                return true;
            }
            case COL_WEATHER_DATE: {
                String dateString = cursor.getString(columnIndex);
                TextView dateView = (TextView) view;
                dateView.setText(Utility.formatDate(dateString));
                return true;
            }
            }
            return false;
        }
    });

    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    // Get a reference to the ListView, and attach this adapter to it.
    ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
    listView.setAdapter(mForecastAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            SimpleCursorAdapter adapter = (SimpleCursorAdapter) adapterView.getAdapter();
            Cursor cursor = adapter.getCursor();
            if (cursor != null && cursor.moveToPosition(position)) {
                String dateString = Utility.formatDate(cursor.getString(COL_WEATHER_DATE));
                String weatherDescription = cursor.getString(COL_WEATHER_DESC);

                boolean isMetric = Utility.isMetric(getActivity());
                String high = Utility.formatTemperature(cursor.getDouble(COL_WEATHER_MAX_TEMP), isMetric);
                String low = Utility.formatTemperature(cursor.getDouble(COL_WEATHER_MIN_TEMP), isMetric);

                String detailString = String.format("%s - %s - %s/%s", dateString, weatherDescription, high,
                        low);

                Intent intent = new Intent(getActivity(), DetailActivity.class).putExtra(Intent.EXTRA_TEXT,
                        detailString);
                startActivity(intent);
            }
        }
    });

    return rootView;
}

From source file:miguelmaciel.play.anonymouscall.ui.ContactsListFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // This swaps the new cursor into the adapter.
    if (loader.getId() == ContactsQuery.QUERY_ID) {
        mAdapter.swapCursor(data);//from  w  w w  .j a va  2 s  .c om

        // If this is a two-pane layout and there is a search query then
        // there is some additional work to do around default selected
        // search item.
        if (mIsTwoPaneLayout && !TextUtils.isEmpty(mSearchTerm) && mSearchQueryChanged) {
            // Selects the first item in results, unless this fragment has
            // been restored from a saved state (like orientation change)
            // in which case it selects the previously selected search item.
            if (data != null && data.moveToPosition(mPreviouslySelectedSearchItem)) {
                // Creates the content Uri for the previously selected contact by appending the
                // contact's ID to the Contacts table content Uri
                final Uri uri = Uri.withAppendedPath(Contacts.CONTENT_URI,
                        String.valueOf(data.getLong(ContactsQuery.ID)));
                mOnContactSelectedListener.onContactSelected(uri);
                getListView().setItemChecked(mPreviouslySelectedSearchItem, true);
            } else {
                // No results, clear selection.
                onSelectionCleared();
            }
            // Only restore from saved state one time. Next time fall back
            // to selecting first item. If the fragment state is saved again
            // then the currently selected item will once again be saved.
            mPreviouslySelectedSearchItem = 0;
            mSearchQueryChanged = false;
        }

        //This method will get all Names and respective phone numbers to an array [arrID/arrPhones]
        if (data.getCount() > 0) {
            //Clear the arrays
            arrID.clear();
            arrPhones.clear();
            //Go to first position of the array and start getting the data
            data.moveToFirst();
            do {
                String contactId = data.getString(data.getColumnIndex(Contacts._ID));
                //
                //  Get all phone numbers.
                //
                Cursor phones = null;
                try {
                    phones = getActivity().getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);

                    if (phones.getCount() > 0) {
                        phones.moveToFirst();
                        do {
                            String number = phones.getString(
                                    phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            int type = phones
                                    .getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                            switch (type) {
                            case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
                                // do something with the Home number here...
                                arrID.add(contactId);
                                arrPhones.add(number);
                                break;
                            case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
                                // do something with the Mobile number here...
                                arrID.add(contactId);
                                arrPhones.add(number);
                                break;
                            case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
                                // do something with the Work number here...
                                arrID.add(contactId);
                                arrPhones.add(number);
                                break;
                            }
                        } while (phones.moveToNext());
                        // phones.close();
                    }
                } catch (Throwable e) {
                    phones.close();
                } finally {
                    phones.close();
                }
            } while (data.moveToNext());
        }
    }
}

From source file:com.silentcircle.contacts.calllognew.CallLogAdapter.java

/**
 * Retrieves the day group of the previous call in the call log.  Used to determine if the day
 * group has changed and to trigger display of the day group text.
 *
 * @param cursor The call log cursor./*w  w w . j  a  v a 2 s .c o  m*/
 * @return The previous day group, or DAY_GROUP_NONE if this is the first call.
 */
private int getPreviousDayGroup(Cursor cursor) {
    // We want to restore the position in the cursor at the end.
    int startingPosition = cursor.getPosition();
    int dayGroup = CallLogGroupBuilder.DAY_GROUP_NONE;
    if (cursor.moveToPrevious()) {
        long previousRowId = cursor.getLong(CallLogQuery.ID);
        dayGroup = getDayGroupForCall(previousRowId);
    }
    cursor.moveToPosition(startingPosition);
    return dayGroup;
}

From source file:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactsListFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    /**// w  w  w. java  2 s.  c  o  m
     * This swaps the new cursor into the adapter. This is the point when the cursor data is passed on to the adapter. 
     */
    if (loader.getId() == ContactsQuery.QUERY_ID) {
        mAdapter.swapCursor(data);

        // If this is a two-pane layout and there is a search query then
        // there is some additional work to do around default selected
        // search item.
        if (mIsTwoPaneLayout && !TextUtils.isEmpty(mSearchTerm) && mSearchQueryChanged) {
            // Selects the first item in results, unless this fragment has
            // been restored from a saved state (like orientation change)
            // in which case it selects the previously selected search item.
            if (data != null && data.moveToPosition(mPreviouslySelectedSearchItem)) {
                // Creates the content Uri for the previously selected contact by appending the
                // contact's ID to the Contacts table content Uri
                final Uri uri = Uri.withAppendedPath(Contacts.CONTENT_URI,
                        String.valueOf(data.getLong(ContactsQuery.ID)));
                mOnContactSelectedListener.onContactSelected(uri);
                getListView().setItemChecked(mPreviouslySelectedSearchItem, true);
            } else {
                // No results, clear selection.
                onSelectionCleared();
            }
            // Only restore from saved state one time. Next time fall back
            // to selecting first item. If the fragment state is saved again
            // then the currently selected item will once again be saved.
            mPreviouslySelectedSearchItem = 0;
            mSearchQueryChanged = false;
        }
    }
}

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

/**
 * Launches an intent based on a suggestion.
 *
 * @param position The index of the suggestion to create the intent from.
 * @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 true if a successful launch, false if could not (e.g. bad position).
 *//*from   www .ja  v a2 s. c om*/
private boolean launchSuggestion(int position, int actionKey, String actionMsg) {
    Cursor c = mSuggestionsAdapter.getCursor();
    if ((c != null) && c.moveToPosition(position)) {

        Intent intent = createIntentFromSuggestion(c, actionKey, actionMsg);

        // launch the intent
        launchIntent(intent);

        return true;
    }
    return false;
}