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:org.andstatus.app.msg.TimelineActivity.java

/**
 * @param position Of current item in the underlying Cursor
 * @return id of the User linked to this message. This link reflects the User's timeline 
 * or an Account which was used to retrieved the message
 *///from w  w  w. java  2s .  c  om
@Override
public long getLinkedUserIdFromCursor(int position) {
    long userId = 0;
    try {
        Cursor cursor = null;
        if (getListAdapter() != null) {
            cursor = ((CursorAdapter) getListAdapter()).getCursor();
        }
        if (cursor != null && !cursor.isClosed()) {
            cursor.moveToPosition(position);
            int columnIndex = cursor.getColumnIndex(User.LINKED_USER_ID);
            if (columnIndex > -1) {
                userId = cursor.getLong(columnIndex);
            }
        }
    } catch (Exception e) {
        MyLog.v(this, e);
    }
    return userId;
}

From source file:prince.app.sphotos.util.ImageWorker.java

public Bitmap loadImageThumbNailFromSDCard(Object params) {
    Bitmap bitmap = null;//from  w  w  w.  j  a  v  a  2  s.c  o m
    Uri uri = null;
    int columnIndex = 0;

    // Set up an array of the  Image ID column we want
    String[] projection = { MediaStore.Images.Thumbnails._ID };

    // Create the cursor pointing to the SDCard
    Cursor cursor = mContext.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
            projection, // Which columns to return
            null, // Return all rows
            null, MediaStore.Images.Thumbnails._ID);

    if (cursor != null) {
        columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
        int size = cursor.getCount();

        // If size is 0, there are no images on the SD Card.
        if (size == 0) {
            //   Context context = getApplicationContext();
            CharSequence text = "No Images Found!";
            int duration = Toast.LENGTH_LONG;
            Toast.makeText(mContext, text, duration).show();
            ((Activity) mContext).finish(); // close the activity
        }

        int imageID = 0;
        cursor.moveToPosition((Integer) params);
        imageID = cursor.getInt(columnIndex);
        uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
        Log.d(TAG, uri.getPath());
        try {
            // First decode with inJustDecodeBounds=true to check dimensions
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(uri), null, options);

            // Calculate inSampleSize
            options.inSampleSize = ImageResizer.calculateInSampleSize(options, 110, 110);
            if (Global.hasHoneycomb()) {
                ImageResizer.addInBitmapOptions(options, mImageCache);
            }

            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeStream(mContext.getContentResolver().openInputStream(uri), null,
                    options);
            if (bitmap != null) {
                cursor.close();
                return bitmap;
            }
        } catch (IOException e) {
            //Error fetching image, try to recover
            //   return loadImageThumbNailFromSDCard(params);
        }
    }

    cursor.close();
    return null;
}

From source file:com.money.manager.ex.common.AllDataListFragment.java

private Money getTotalFromCursor(Cursor cursor) {
    Money total = MoneyFactory.fromString("0");
    int originalPosition = cursor.getPosition();
    AllDataAdapter adapter = getAllDataAdapter();
    CurrencyService currencyService = new CurrencyService(getContext());
    int baseCurrencyId = currencyService.getBaseCurrencyId();
    ContentValues values = new ContentValues();

    int currencyId;
    Money amount;/*ww w  .  j av  a 2  s. c  o m*/
    Money converted;
    String transType;
    TransactionTypes transactionType;

    cursor.moveToPosition(Constants.NOT_SET);

    while (cursor.moveToNext()) {
        values.clear();

        // Read needed data.
        DatabaseUtils.cursorStringToContentValues(cursor, adapter.TRANSACTIONTYPE, values);
        DatabaseUtils.cursorIntToContentValues(cursor, adapter.CURRENCYID, values);
        DatabaseUtils.cursorIntToContentValues(cursor, adapter.TOCURRENCYID, values);
        DatabaseUtils.cursorDoubleToCursorValues(cursor, adapter.AMOUNT, values);
        DatabaseUtils.cursorDoubleToCursorValues(cursor, adapter.TOAMOUNT, values);

        transType = values.getAsString(adapter.TRANSACTIONTYPE);
        transactionType = TransactionTypes.valueOf(transType);

        if (transactionType.equals(TransactionTypes.Transfer)) {
            currencyId = values.getAsInteger(adapter.TOCURRENCYID);
            amount = MoneyFactory.fromString(values.getAsString(adapter.TOAMOUNT));
        } else {
            currencyId = values.getAsInteger(adapter.CURRENCYID);
            amount = MoneyFactory.fromString(values.getAsString(adapter.AMOUNT));
        }

        converted = currencyService.doCurrencyExchange(baseCurrencyId, amount, currencyId);
        total = total.add(converted);
    }

    cursor.moveToPosition(originalPosition);

    return total;
}

From source file:com.visva.voicerecorder.view.fragments.FragmentContact.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 v  a 2s . com*/

        // 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);
                mListContact.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:com.tavant.droid.womensecurity.fragments.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);//ww w .  j av  a  2  s .com

        if (!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:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactsListFragment.java

private void getData() {
    Cursor data = getContacts();
    mAdapter.swapCursor(data);// w ww  .  jav  a2  s  .c  o  m

    // 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:com.alboteanu.android.sunshine.app.ForecastFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    mForecastAdapter.swapCursor(data);/*from   www . j  av  a  2  s .c  o m*/
    updateEmptyView();
    if (data.getCount() == 0) {
        getActivity().supportStartPostponedEnterTransition();
    } else {
        mRecyclerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                // Since we know we're going to get items, we keep the listener around until
                // we see Children.
                if (mRecyclerView.getChildCount() > 0) {
                    mRecyclerView.getViewTreeObserver().removeOnPreDrawListener(this);
                    int position = mForecastAdapter.getSelectedItemPosition();
                    if (position == RecyclerView.NO_POSITION && -1 != mInitialSelectedDate) {
                        Cursor data = mForecastAdapter.getCursor();
                        int count = data.getCount();
                        int dateColumn = data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_DATE);
                        for (int i = 0; i < count; i++) {
                            data.moveToPosition(i);
                            if (data.getLong(dateColumn) == mInitialSelectedDate) {
                                position = i;
                                break;
                            }
                        }
                    }
                    if (position == RecyclerView.NO_POSITION)
                        position = 0;
                    // If we don't need to restart the loader, and there's a desired position to restore
                    // to, do so now.
                    mRecyclerView.smoothScrollToPosition(position);
                    RecyclerView.ViewHolder vh = mRecyclerView.findViewHolderForAdapterPosition(position);
                    if (null != vh && mAutoSelectView) {
                        mForecastAdapter.selectView(vh);
                    }
                    if (mHoldForTransition) {
                        getActivity().supportStartPostponedEnterTransition();
                    }
                    return true;
                }
                return false;
            }
        });
    }

}

From source file:com.example.android.sunshineapp.ForecastFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    mForecastAdapter.swapCursor(data);//ww w.  j  a  v  a 2s  . co m
    updateEmptyView();
    if (data.getCount() == 0) {
        getActivity().supportStartPostponedEnterTransition();
    } else {
        mRecyclerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                // Since we know we're going to get items, we keep the listener around until
                // we see Children.
                if (mRecyclerView.getChildCount() > 0) {
                    mRecyclerView.getViewTreeObserver().removeOnPreDrawListener(this);
                    int position = mForecastAdapter.getSelectedItemPosition();
                    if (position == RecyclerView.NO_POSITION && -1 != mInitialSelectedDate) {
                        Cursor data = mForecastAdapter.getCursor();
                        int count = data.getCount();
                        int dateColumn = data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_DATE);
                        for (int i = 0; i < count; i++) {
                            data.moveToPosition(i);
                            if (data.getLong(dateColumn) == mInitialSelectedDate) {
                                position = i;
                                break;
                            }
                        }
                    }
                    if (position == RecyclerView.NO_POSITION)
                        position = 0;

                    mRecyclerView.smoothScrollToPosition(position);
                    RecyclerView.ViewHolder vh = mRecyclerView.findViewHolderForAdapterPosition(position);
                    if (null != vh && mAutoSelectView) {
                        mForecastAdapter.selectView(vh);
                    }
                    if (mHoldForTransition) {
                        getActivity().supportStartPostponedEnterTransition();
                    }
                    return true;
                }
                return false;
            }
        });
    }

}

From source file:android.com.example.contactslist.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   www . j  a v  a 2s.  c  o m

        // 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:com.android.contacts.list.ContactEntryListAdapter.java

/**
 * Updates partitions according to the directory meta-data contained in the supplied
 * cursor.//from  w  w  w .j a  v  a2  s  .  c  o m
 */
public void changeDirectories(Cursor cursor) {
    if (cursor.getCount() == 0) {
        // Directory table must have at least local directory, without which this adapter will
        // enter very weird state.
        Log.e(TAG, "Directory search loader returned an empty cursor, which implies we have "
                + "no directory entries.", new RuntimeException());
        return;
    }
    HashSet<Long> directoryIds = new HashSet<Long>();

    int idColumnIndex = cursor.getColumnIndex(Directory._ID);
    int directoryTypeColumnIndex = cursor.getColumnIndex(DirectoryListLoader.DIRECTORY_TYPE);
    int displayNameColumnIndex = cursor.getColumnIndex(Directory.DISPLAY_NAME);
    int photoSupportColumnIndex = cursor.getColumnIndex(Directory.PHOTO_SUPPORT);

    // TODO preserve the order of partition to match those of the cursor
    // Phase I: add new directories
    cursor.moveToPosition(-1);
    while (cursor.moveToNext()) {
        long id = cursor.getLong(idColumnIndex);
        directoryIds.add(id);
        if (getPartitionByDirectoryId(id) == -1) {
            DirectoryPartition partition = new DirectoryPartition(false, true);
            partition.setDirectoryId(id);
            partition.setDirectoryType(cursor.getString(directoryTypeColumnIndex));
            partition.setDisplayName(cursor.getString(displayNameColumnIndex));
            int photoSupport = cursor.getInt(photoSupportColumnIndex);
            partition.setPhotoSupported(photoSupport == Directory.PHOTO_SUPPORT_THUMBNAIL_ONLY
                    || photoSupport == Directory.PHOTO_SUPPORT_FULL);
            addPartition(partition);
        }
    }

    // Phase II: remove deleted directories
    int count = getPartitionCount();
    for (int i = count; --i >= 0;) {
        Partition partition = getPartition(i);
        if (partition instanceof DirectoryPartition) {
            long id = ((DirectoryPartition) partition).getDirectoryId();
            if (!directoryIds.contains(id)) {
                removePartition(i);
            }
        }
    }

    invalidate();
    notifyDataSetChanged();
}