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.wuman.androidimageloader.ImageLoader.java

/**
 * Pre-fetches the binary content for images referenced by a {@link Cursor},
 * without loading the image data into memory.
 * <p>//from  w w  w  . j  a va 2s.  c  om
 * Pre-fetching should not be used unless a {@link ContentHandler} with
 * support for persistent caching was passed to the constructor.
 * <p>
 * Typically, an {@link Activity} would register a {@link DataSetObserver}
 * and call this method from {@link DataSetObserver#onChanged()} to load
 * off-screen images into a file-based cache when they are not already
 * present in the cache.
 * 
 * @param cursor
 *            the {@link Cursor} containing the image URLs.
 * @param columnIndex
 *            the column index of the image URL. The column value may be
 *            {@code NULL}.
 * @see #prefetch(String)
 */
public void prefetch(Cursor cursor, int columnIndex) {
    for (int position = 0; cursor.moveToPosition(position); position++) {
        String url = cursor.getString(columnIndex);
        if (!TextUtils.isEmpty(url)) {
            prefetch(url);
        }
    }
}

From source file:ca.rmen.android.poetassistant.wotd.WotdLoader.java

@Override
public ResultListData<WotdEntry> loadInBackground() {
    Log.d(TAG, "loadInBackground()");

    List<WotdEntry> data = new ArrayList<>(100);

    Cursor cursor = mDictionary.getRandomWordCursor();
    if (cursor == null || cursor.getCount() == 0)
        return emptyResult();

    try {//from www. ja v a 2 s .co m
        Set<String> favorites = mFavorites.getFavorites();
        Calendar calendar = Wotd.getTodayUTC();
        Calendar calendarDisplay = Wotd.getTodayUTC();
        calendarDisplay.setTimeZone(TimeZone.getDefault());
        Settings.Layout layout = Settings.getLayout(mPrefs);
        for (int i = 0; i < 100; i++) {
            Random random = new Random();
            random.setSeed(calendar.getTimeInMillis());
            String date = DateUtils.formatDateTime(getContext(), calendarDisplay.getTimeInMillis(),
                    DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            int position = random.nextInt(cursor.getCount());
            if (cursor.moveToPosition(position)) {
                String word = cursor.getString(0);
                @ColorRes
                int color = (i % 2 == 0) ? R.color.row_background_color_even : R.color.row_background_color_odd;
                data.add(new WotdEntry(word, date, ContextCompat.getColor(getContext(), color),
                        favorites.contains(word), layout == Settings.Layout.EFFICIENT));
            }
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            calendarDisplay.add(Calendar.DAY_OF_YEAR, -1);

        }

    } finally {
        cursor.close();
    }
    return new ResultListData<>(getContext().getString(R.string.wotd_list_header), false, data);
}

From source file:org.opendatakit.services.instance.provider.InstanceProvider.java

/**
 * This method removes the entry from the content provider, and also removes
 * any associated files. files: form.xml, [formmd5].formdef, formname
 * {directory}//from  ww w . ja  va 2s  . c  o m
 */
@Override
public synchronized int delete(@NonNull Uri uri, String where, String[] whereArgs) {
    possiblyWaitForContentProviderDebugger();

    List<String> segments = uri.getPathSegments();

    if (segments.size() < 2 || segments.size() > 3) {
        throw new SQLException("Unknown URI (too many segments!) " + uri);
    }

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    String tableId = segments.get(1);
    // _ID in UPLOADS_TABLE_NAME
    String instanceId = (segments.size() == 3 ? segments.get(2) : null);

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    List<IdStruct> idStructs = new ArrayList<IdStruct>();
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName,
                dbHandleName);
        db.beginTransactionNonExclusive();

        boolean success = false;
        try {
            success = ODKDatabaseImplUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            WebLogger.getLogger(appName).printStackTrace(e);
            throw new SQLException("Unknown URI (exception testing for tableId) " + uri);
        }

        if (success) {
            // delete the entries matching the filter criteria
            if (segments.size() == 2) {
                where = "(" + where + ") AND (" + InstanceColumns.DATA_INSTANCE_ID + "=? )";
                if (whereArgs != null) {
                    String[] args = new String[whereArgs.length + 1];
                    System.arraycopy(whereArgs, 0, args, 0, whereArgs.length);
                    args[whereArgs.length] = instanceId;
                    whereArgs = args;
                } else {
                    whereArgs = new String[] { instanceId };
                }
            }

            internalUpdate(db, uri, appName, tableId);

            Cursor del = null;
            try {
                del = internalQuery(db, uri, appName, tableId, instanceId, null, where, whereArgs, null);
                del.moveToPosition(-1);
                while (del.moveToNext()) {
                    String iId = CursorUtils.getIndexAsString(del, del.getColumnIndex(InstanceColumns._ID));
                    String iIdDataTable = CursorUtils.getIndexAsString(del,
                            del.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID));
                    idStructs.add(new IdStruct(iId, iIdDataTable));
                    String path = ODKFileUtils.getInstanceFolder(appName, tableId, iIdDataTable);
                    File f = new File(path);
                    if (f.exists()) {
                        if (f.isDirectory()) {
                            FileUtils.deleteDirectory(f);
                        } else {
                            f.delete();
                        }
                    }

                }
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
                throw new IllegalArgumentException("Unable to delete instance directory: " + e.toString());
            } finally {
                if (del != null) {
                    del.close();
                }
            }
        } else {
            // delete anything we find, since the table doesn't exist
            Cursor del = null;
            try {
                where = InstanceColumns.DATA_TABLE_TABLE_ID + "=?";
                whereArgs = new String[] { tableId };
                del = db.query(DatabaseConstants.UPLOADS_TABLE_NAME, null, where, whereArgs, null, null, null,
                        null);
                del.moveToPosition(-1);
                while (del.moveToNext()) {
                    String iId = CursorUtils.getIndexAsString(del, del.getColumnIndex(InstanceColumns._ID));
                    String iIdDataTable = CursorUtils.getIndexAsString(del,
                            del.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID));
                    idStructs.add(new IdStruct(iId, iIdDataTable));
                    String path = ODKFileUtils.getInstanceFolder(appName, tableId, iIdDataTable);
                    File f = new File(path);
                    if (f.exists()) {
                        if (f.isDirectory()) {
                            FileUtils.deleteDirectory(f);
                        } else {
                            f.delete();
                        }
                    }
                }
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
                throw new IllegalArgumentException("Unable to delete instance directory: " + e.toString());
            } finally {
                if (del != null) {
                    del.close();
                }
            }
        }

        for (IdStruct idStruct : idStructs) {
            db.delete(DatabaseConstants.UPLOADS_TABLE_NAME, InstanceColumns.DATA_INSTANCE_ID + "=?",
                    new String[] { idStruct.idUploadsTable });
            db.delete(tableId, DATA_TABLE_ID_COLUMN + "=?", new String[] { idStruct.idDataTable });
        }
        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            try {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
            } finally {
                try {
                    db.releaseReference();
                } finally {
                    // this closes the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName,
                            dbHandleName);
                }
            }
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return idStructs.size();
}

From source file:fr.mixit.android.ui.adapters.MyPlanningAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    final PlanningViewHolder holder = (PlanningViewHolder) view.getTag();

    if (cursor != null) {
        final int oldPosition = cursor.getPosition();
        final long start = cursor.getLong(MixItContract.Sessions.PROJ_PLANNING.START);
        final String header = (String) DateUtils.formatPlanningHeader(start);

        long oldStart = 0;
        String oldHeader = null;//  w w w .  j a v a 2 s  . co m
        if (cursor.moveToPrevious()) {
            oldStart = cursor.getLong(MixItContract.Sessions.PROJ_PLANNING.START);
            oldHeader = (String) DateUtils.formatPlanningHeader(oldStart);
        }

        if (header.equalsIgnoreCase(oldHeader)) {
            holder.mHeader.setVisibility(View.GONE);
        } else {
            holder.mHeader.setVisibility(View.VISIBLE);
            holder.mHeader.setText(header);
        }

        cursor.moveToPosition(oldPosition);
    }

    holder.mTalk.setContentPlanning(cursor, mDisplayPastSessionsInGrey);
}

From source file:org.mozilla.gecko.AwesomeBarTabs.java

private void handleBookmarkItemClick(int position) {
    // If we tap on the header view, go up a level
    if (position == 0) {
        mBookmarksAdapter.moveToParentFolder();
        return;// w w w .j  a  v a  2 s .  com
    }

    Cursor cursor = mBookmarksAdapter.getCursor();
    // The header view takes up a spot in the list
    cursor.moveToPosition(position - 1);

    int isFolder = cursor.getInt(cursor.getColumnIndexOrThrow(Bookmarks.IS_FOLDER));
    if (isFolder == 1) {
        // If we're clicking on a folder, update mBookmarksAdapter to move to that folder
        int folderId = cursor.getInt(cursor.getColumnIndexOrThrow(Bookmarks._ID));
        String folderTitle = mBookmarksAdapter.getFolderTitle(position - 1);

        mBookmarksAdapter.moveToChildFolder(folderId, folderTitle);
        return;
    }

    // Otherwise, just open the URL
    String url = cursor.getString(cursor.getColumnIndexOrThrow(URLColumns.URL));
    if (mUrlOpenListener != null)
        mUrlOpenListener.onUrlOpen(url);
}

From source file:com.tuxpan.foregroundcameragalleryplugin.ForegroundCameraLauncher.java

private int getImageOrientation(Uri uri) {
    String[] cols = { MediaStore.Images.Media.ORIENTATION };
    Cursor cursor = cordova.getActivity().getContentResolver().query(uri, cols, null, null, null);
    int rotate = 0;
    if (cursor != null) {
        cursor.moveToPosition(0);
        rotate = cursor.getInt(0);//  ww  w . j av a2 s.  co  m
        cursor.close();
    }
    return rotate;
}

From source file:com.google.android.apps.muzei.gallery.GalleryArtSource.java

private void publishNextArtwork(Uri forceUri) {
    // schedule next
    scheduleNext();/*from  w w  w .j a v a 2s.c  o m*/

    Cursor chosenUris = getContentResolver().query(GalleryContract.ChosenPhotos.CONTENT_URI,
            new String[] { BaseColumns._ID }, null, null, null);
    int numChosenUris = (chosenUris != null) ? chosenUris.getCount() : 0;

    Artwork currentArtwork = getCurrentArtwork();
    String lastToken = (currentArtwork != null) ? currentArtwork.getToken() : null;

    Uri imageUri;
    Random random = new Random();
    if (forceUri != null) {
        imageUri = forceUri;

    } else if (numChosenUris > 0) {
        while (true) {
            chosenUris.moveToPosition(random.nextInt(chosenUris.getCount()));
            imageUri = ContentUris.withAppendedId(GalleryContract.ChosenPhotos.CONTENT_URI,
                    chosenUris.getLong(chosenUris.getColumnIndex(BaseColumns._ID)));
            if (numChosenUris <= 1 || !imageUri.toString().equals(lastToken)) {
                break;
            }
        }
    } else {
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            Log.w(TAG, "Missing read external storage permission.");
            return;
        }
        Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.MediaColumns._ID },
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME + " NOT LIKE '%Screenshots%'", null, null);
        if (cursor == null) {
            Log.w(TAG, "Empty cursor.");
            return;
        }

        int count = cursor.getCount();
        if (count == 0) {
            Log.e(TAG, "No photos in the gallery.");
            return;
        }

        while (true) {
            cursor.moveToPosition(random.nextInt(count));
            imageUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    cursor.getLong(0));
            if (!imageUri.toString().equals(lastToken)) {
                break;
            }
        }

        cursor.close();
    }
    if (chosenUris != null) {
        chosenUris.close();
    }

    String token = imageUri.toString();

    // Retrieve metadata for item
    ensureMetadataExists(imageUri);
    String[] projection = { GalleryContract.MetadataCache.COLUMN_NAME_DATETIME,
            GalleryContract.MetadataCache.COLUMN_NAME_LOCATION };
    Cursor metadata = getContentResolver().query(GalleryContract.MetadataCache.CONTENT_URI, projection,
            GalleryContract.MetadataCache.COLUMN_NAME_URI + "=?", new String[] { imageUri.toString() }, null);
    long datetime = 0;
    String location = null;
    if (metadata != null && metadata.moveToFirst()) {
        datetime = metadata
                .getLong(metadata.getColumnIndex(GalleryContract.MetadataCache.COLUMN_NAME_DATETIME));
        location = metadata
                .getString(metadata.getColumnIndex(GalleryContract.MetadataCache.COLUMN_NAME_LOCATION));
    }
    if (metadata != null) {
        metadata.close();
    }

    // Publish the actual artwork
    String title;
    if (datetime > 0) {
        title = DateUtils.formatDateTime(this, datetime,
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY);
    } else {
        title = getString(R.string.gallery_from_gallery);
    }

    String byline;
    if (!TextUtils.isEmpty(location)) {
        byline = location;
    } else {
        byline = getString(R.string.gallery_touch_to_view);
    }

    publishArtwork(new Artwork.Builder().imageUri(imageUri).title(title).byline(byline).token(token)
            .viewIntent(new Intent(Intent.ACTION_VIEW).setDataAndType(imageUri, "image/jpeg")).build());
}

From source file:com.forktech.cmerge.ui.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();

    // Moves to the Cursor row corresponding to the ListView item that was
    // clicked/*  ww  w . jav  a 2  s . c  om*/
    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.
    mOnContactSelectedListener.onContactSelected(uri);

    // 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.visva.voicerecorder.view.fragments.FragmentContact.java

private void deleteThisContact(int selectedPosition) {
    String deleteTitle = getActivity().getString(R.string.delete);
    String contentMsg = getActivity().getString(R.string.are_you_sure_to_delete_contact);
    String cancel = getActivity().getString(R.string.cancel);
    final Cursor cursor = mAdapter.getCursor();
    if (cursor == null)
        return;/*from ww w.  j  av  a  2  s .  c o m*/
    // Moves to the Cursor row corresponding to the ListView item that was clicked
    cursor.moveToPosition(selectedPosition);

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

    Dialog dialog = new Dialog(getActivity(), deleteTitle, contentMsg);
    dialog.addCancelButton(cancel, new OnClickListener() {

        @Override
        public void onClick(View v) {
        }
    });
    dialog.setOnAcceptButtonClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Utils.deleteContact(getActivity(), uri);
        }
    });

    dialog.getButtonAccept();

    dialog.show();
}

From source file:org.dvbviewer.controller.ui.fragments.ChannelList.java

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    if (mCHannelSelectedListener != null) {
        selectedPosition = position;//from  w  w w .j a v  a 2 s. c  om
        Cursor c = mAdapter.getCursor();
        c.moveToPosition(position);
        Channel chan = cursorToChannel(c);
        ArrayList<Channel> chans = cursorToChannellist(position);
        mCHannelSelectedListener.channelSelected(chans, chan, position);
        getListView().setItemChecked(position, true);
    } else {
        Intent epgPagerIntent = new Intent(getActivity(),
                org.dvbviewer.controller.ui.phone.EpgPagerActivity.class);
        // long[] feedIds = new long[data.getCount()];

        ArrayList<Channel> chans = cursorToChannellist(position);

        epgPagerIntent.putParcelableArrayListExtra(Channel.class.getName(), chans);
        epgPagerIntent.putExtra("position", position);
        startActivity(epgPagerIntent);
        selectedPosition = ListView.INVALID_POSITION;
    }
}