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:edu.mit.mobile.android.livingpostcards.CardMediaEditFragment.java

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    switch (v.getId()) {
    case R.id.gallery: {
        getActivity().getMenuInflater().inflate(R.menu.context_card_media, menu);
        final Cursor c = mAdapter.getCursor();
        if (c == null) {
            return;
        }/*from  www  . j  a  va2  s  . c o m*/
        AdapterView.AdapterContextMenuInfo info;
        try {
            info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (final ClassCastException e) {
            Log.e(TAG, "bad menuInfo", e);
            return;
        }

        // the below is a special case due to a bug in the infinite gallery spinner.

        c.moveToPosition(info.position % mAdapter.getCount());

        final String myUserUri = Authenticator.getUserUri(getActivity());

        final boolean isEditable = Authorable.canEdit(myUserUri, c);

        menu.findItem(R.id.delete).setVisible(isEditable);

    }
        break;
    default:
        super.onCreateContextMenu(menu, v, menuInfo);
    }

}

From source file:com.silentcircle.contacts.interactions.ContactDeletionInteraction.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    if (mDialog != null) {
        mDialog.dismiss();//from   w  ww . j a  v a2s .c  o  m
        mDialog = null;
    }

    if (!mActive) {
        return;
    }

    long contactId = 0;

    // This cursor may contain duplicate raw contacts, so we need to de-dupe them first
    HashSet<Long> readOnlyRawContacts = Sets.newHashSet();
    HashSet<Long> writableRawContacts = Sets.newHashSet();

    AccountTypeManager accountTypes = AccountTypeManager.getInstance(getActivity());
    cursor.moveToPosition(-1);
    while (cursor.moveToNext()) {
        contactId = cursor.getLong(COLUMN_INDEX_RAW_CONTACT_ID);
        AccountType type = accountTypes.getAccountType();
        boolean writable = type == null || type.areContactsWritable();
        if (writable) {
            writableRawContacts.add(contactId);
        } else {
            readOnlyRawContacts.add(contactId);
        }
    }

    int readOnlyCount = readOnlyRawContacts.size();
    int writableCount = writableRawContacts.size();
    if (readOnlyCount > 0 && writableCount > 0) {
        mMessageId = R.string.readOnlyContactDeleteConfirmation;
    } else if (readOnlyCount > 0 && writableCount == 0) {
        mMessageId = R.string.readOnlyContactWarning;
    } else if (readOnlyCount == 0 && writableCount > 1) {
        mMessageId = R.string.multipleContactDeleteConfirmation;
    } else {
        mMessageId = R.string.deleteConfirmation;
    }

    final Uri contactUri = RawContacts.getLookupUri(contactId);
    showDialog(mMessageId, contactUri);

    // We don't want onLoadFinished() calls any more, which may come when the database is
    // updating.
    getLoaderManager().destroyLoader(R.id.dialog_delete_contact_loader_id);
}

From source file:fi.hut.soberit.sensors.services.BatchDataUploadService.java

protected void writeSession(final FileWriter destination, final Session session, boolean lastSession)
        throws IOException {

    final DatabaseHelper shardHelper = new DatabaseHelper(BatchDataUploadService.this, session.getId());
    final SQLiteDatabase db = shardHelper.getReadableDatabase();

    final Cursor rowCursor = db.query(DatabaseHelper.OBSERVATION_VALUE_TABLE, null, null, null, null, null,
            ObservationValueTable.TIME + " ASC");

    rowCursor.moveToFirst();// w ww . ja  va  2 s  .  co  m

    writeSessionHeader(destination, session, rowCursor);

    Log.d(TAG, "sessions: " + rowCursor.getCount());
    final StringBuilder builder = new StringBuilder();
    for (int row = 0; row < rowCursor.getCount(); row++) {
        rowCursor.moveToPosition(row);

        final GenericObservation observation = ObservationValueTable.observationFromCursor(rowCursor, row);

        final ObservationType type = typesMap.get(observation.getObservationTypeId());
        builder.setLength(0);

        writeObservation(builder, session, observation, type, row + 1 != rowCursor.getCount());

        destination.write(builder.toString());
    } // for(int row = 0; row < rowCursor.getCount(); row++) {

    writeSessionFooter(destination, session, rowCursor);

    rowCursor.close();
    shardHelper.close();

    if (!lastSession) {
        destination.write(",");
    }
}

From source file:org.skt.runtime.original.CameraLauncher.java

/**
 * Called when the camera view exits. //from   w ww .  j av a2 s . c o  m
 * 
 * @param requestCode       The request code originally supplied to startActivityForResult(), 
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // Create an ExifHelper to save the exif data that is lost during compression
    ExifHelper exif = new ExifHelper();
    try {
        if (this.encodingType == JPEG) {
            exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx.getContext()) + "/Pic.jpg");
            exif.readExifData();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Read in bitmap of captured image
                Bitmap bitmap;
                try {
                    bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(),
                            imageUri);
                } catch (FileNotFoundException e) {
                    Uri uri = intent.getData();
                    android.content.ContentResolver resolver = this.ctx.getContentResolver();
                    bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
                }

                bitmap = scaleBitmap(bitmap);

                // If sending base64 image back
                if (destType == DATA_URL) {
                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    // Create entry in media store for image
                    // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
                    ContentValues values = new ContentValues();
                    values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                    Uri uri = null;
                    try {
                        uri = this.ctx.getContentResolver()
                                .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                    } catch (UnsupportedOperationException e) {
                        LOG.d(LOG_TAG, "Can't write to external media storage.");
                        try {
                            uri = this.ctx.getContentResolver().insert(
                                    android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                        } catch (UnsupportedOperationException ex) {
                            LOG.d(LOG_TAG, "Can't write to internal media storage.");
                            this.failPicture("Error capturing image - no media storage found.");
                            return;
                        }
                    }

                    // Add compressed version of captured image to returned media store Uri
                    OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                    os.close();

                    // Restore exif data to file
                    if (this.encodingType == JPEG) {
                        exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
                        exif.writeExifData();
                    }

                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                }
                bitmap.recycle();
                bitmap = null;
                System.gc();

                checkForDuplicateImage(FILE_URI);
            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();
            android.content.ContentResolver resolver = this.ctx.getContentResolver();

            // If you ask for video or all media type you will automatically get back a file URI 
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
            } else {
                // If sending base64 image back
                if (destType == DATA_URL) {
                    try {
                        Bitmap bitmap = android.graphics.BitmapFactory
                                .decodeStream(resolver.openInputStream(uri));
                        String[] cols = { MediaStore.Images.Media.ORIENTATION };
                        Cursor cursor = this.ctx.getContentResolver().query(intent.getData(), cols, null, null,
                                null);
                        if (cursor != null) {
                            cursor.moveToPosition(0);
                            rotate = cursor.getInt(0);
                            cursor.close();
                        }
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            matrix.setRotate(rotate);
                            bitmap = bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                        }
                        bitmap = scaleBitmap(bitmap);
                        this.processPicture(bitmap);
                        bitmap.recycle();
                        bitmap = null;
                        System.gc();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                        this.failPicture("Error retrieving image.");
                    }
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    // Do we need to scale the returned file
                    if (this.targetHeight > 0 && this.targetWidth > 0) {
                        try {
                            Bitmap bitmap = android.graphics.BitmapFactory
                                    .decodeStream(resolver.openInputStream(uri));
                            bitmap = scaleBitmap(bitmap);

                            String fileName = DirectoryManager.getTempDirectoryPath(ctx.getContext())
                                    + "/resize.jpg";
                            OutputStream os = new FileOutputStream(fileName);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                            os.close();

                            // Restore exif data to file
                            if (this.encodingType == JPEG) {
                                exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
                                exif.writeExifData();
                            }

                            bitmap.recycle();
                            bitmap = null;

                            // The resized image is cached by the app in order to get around this and not have to delete you 
                            // application cache I'm adding the current system time to the end of the file url.
                            this.success(
                                    new PluginResult(PluginResult.Status.OK,
                                            ("file://" + fileName + "?" + System.currentTimeMillis())),
                                    this.callbackId);
                            System.gc();
                        } catch (Exception e) {
                            e.printStackTrace();
                            this.failPicture("Error retrieving image.");
                        }
                    } else {
                        this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                    }
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

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

private Bitmap loadFullImageFromSDCard(Object params) {
    Bitmap bitmap = null;/*from ww  w  .ja v a  2s.  co  m*/
    int columnIndex = 0;
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = mContext.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
            projection, null, null, null);

    if (cursor != null) {
        columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToPosition((Integer) params);
        String imagePath = cursor.getString(columnIndex);

        FileInputStream is = null;
        BufferedInputStream bis = null;
        try {
            is = new FileInputStream(new File(imagePath));
            bis = new BufferedInputStream(is);

            bitmap = BitmapFactory.decodeStream(bis);
            cursor.close();
            return bitmap;
        } catch (Exception e) {
            //Try to recover
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (is != null) {
                    is.close();
                }
                cursor.close();
                projection = null;
            } catch (Exception e) {
            }
        }
    }
    return bitmap;
}

From source file:com.ultramegasoft.flavordex2.fragment.ViewInfoFragment.java

@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) {
    final int id = loader.getId();
    switch (id) {
    case LOADER_MAIN:
        if (data.moveToFirst()) {
            mEntryCat = data.getString(data.getColumnIndex(Tables.Entries.CAT));
            mTitle = data.getString(data.getColumnIndex(Tables.Entries.TITLE));
            mRating = data.getFloat(data.getColumnIndex(Tables.Entries.RATING));
            populateViews(data);/*  w ww  .j a  va2s . c  o  m*/
        }
        break;
    case LOADER_EXTRAS:
        data.moveToPosition(-1);
        final LinkedHashMap<String, ExtraFieldHolder> extras = new LinkedHashMap<>();
        String name;
        String value;
        boolean preset;
        while (data.moveToNext()) {
            name = data.getString(data.getColumnIndex(Tables.Extras.NAME));
            value = data.getString(data.getColumnIndex(Tables.EntriesExtras.VALUE));
            preset = data.getInt(data.getColumnIndex(Tables.Extras.PRESET)) == 1;
            extras.put(name, new ExtraFieldHolder(0, name, preset, value));
        }
        populateExtras(extras);
    }
}

From source file:fr.shywim.antoinedaniel.ui.fragment.VideoDetailsFragment.java

private void displayMusics(ViewGroup layout, Cursor cursor) {
    if (layout != null) {
        layout.removeAllViews();/*www  .  ja  va2s.  co  m*/
    }
    if (cursor.getCount() <= 0 || layout == null) {
        return;
    }

    for (int i = 0; i < cursor.getCount(); i++) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.list_music_item, layout, false);
        cursor.moveToPosition(i);
        bindMusic(view, cursor);
        layout.addView(view);
    }
}

From source file:org.odk.collect.android.tasks.InstanceSyncTask.java

@Override
protected String doInBackground(Void... params) {
    int instance = ++counter;
    Timber.i("[%d] doInBackground begins!", instance);

    try {/*from www  . j a  v a  2s  .  c  o  m*/
        List<String> candidateInstances = new LinkedList<String>();
        File instancesPath = new File(Collect.INSTANCES_PATH);
        if (instancesPath.exists() && instancesPath.isDirectory()) {
            File[] instanceFolders = instancesPath.listFiles();
            if (instanceFolders.length == 0) {
                Timber.i("[%d] Empty instance folder. Stopping scan process.", instance);
                Timber.d(Collect.getInstance().getString(R.string.instance_scan_completed));
                return currentStatus;
            }

            // Build the list of potential path that we need to add to the content provider
            for (File instanceDir : instanceFolders) {
                File instanceFile = new File(instanceDir, instanceDir.getName() + ".xml");
                if (!instanceFile.exists()) {
                    // Look for submission file that might have been manually copied from e.g. Briefcase
                    File submissionFile = new File(instanceDir, "submission.xml");
                    if (submissionFile.exists()) {
                        submissionFile.renameTo(instanceFile);
                    }
                }
                if (instanceFile.exists() && instanceFile.canRead()) {
                    candidateInstances.add(instanceFile.getAbsolutePath());
                } else {
                    Timber.i("[%d] Ignoring: %s", instance, instanceDir.getAbsolutePath());
                }
            }
            Collections.sort(candidateInstances);

            List<String> filesToRemove = new ArrayList<>();

            // Remove all the path that's already in the content provider
            Cursor instanceCursor = null;
            InstancesDao instancesDao = new InstancesDao();
            try {
                String sortOrder = InstanceColumns.INSTANCE_FILE_PATH + " ASC ";
                instanceCursor = instancesDao.getSavedInstancesCursor(sortOrder);
                if (instanceCursor == null) {
                    Timber.e("[%d] Instance content provider returned null", instance);
                    return currentStatus;
                }

                instanceCursor.moveToPosition(-1);

                while (instanceCursor.moveToNext()) {
                    String instanceFilename = instanceCursor
                            .getString(instanceCursor.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
                    String instanceStatus = instanceCursor
                            .getString(instanceCursor.getColumnIndex(InstanceColumns.STATUS));
                    if (candidateInstances.contains(instanceFilename)
                            || instanceStatus.equals(InstanceProviderAPI.STATUS_SUBMITTED)) {
                        candidateInstances.remove(instanceFilename);
                    } else {
                        filesToRemove.add(instanceFilename);
                    }
                }

            } finally {
                if (instanceCursor != null) {
                    instanceCursor.close();
                }
            }

            instancesDao.deleteInstancesFromIDs(filesToRemove);

            final boolean instanceSyncFlag = PreferenceManager
                    .getDefaultSharedPreferences(Collect.getInstance().getApplicationContext())
                    .getBoolean(GeneralKeys.KEY_INSTANCE_SYNC, true);

            int counter = 0;
            // Begin parsing and add them to the content provider
            for (String candidateInstance : candidateInstances) {
                String instanceFormId = getFormIdFromInstance(candidateInstance);
                // only process if we can find the id from the instance file
                if (instanceFormId != null) {
                    Cursor formCursor = null;
                    try {
                        String selection = FormsColumns.JR_FORM_ID + " = ? ";
                        String[] selectionArgs = new String[] { instanceFormId };
                        // retrieve the form definition
                        formCursor = new FormsDao().getFormsCursor(selection, selectionArgs);
                        // TODO: optimize this by caching the previously found form definition
                        // TODO: optimize this by caching unavailable form definition to skip
                        if (formCursor != null && formCursor.moveToFirst()) {
                            String submissionUri = null;
                            if (!formCursor.isNull(formCursor.getColumnIndex(FormsColumns.SUBMISSION_URI))) {
                                submissionUri = formCursor
                                        .getString(formCursor.getColumnIndex(FormsColumns.SUBMISSION_URI));
                            }
                            String jrFormId = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
                            String jrVersion = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.JR_VERSION));
                            String formName = formCursor
                                    .getString(formCursor.getColumnIndex(FormsColumns.DISPLAY_NAME));

                            // add missing fields into content values
                            ContentValues values = new ContentValues();
                            values.put(InstanceColumns.INSTANCE_FILE_PATH, candidateInstance);
                            values.put(InstanceColumns.SUBMISSION_URI, submissionUri);
                            values.put(InstanceColumns.DISPLAY_NAME, formName);
                            values.put(InstanceColumns.JR_FORM_ID, jrFormId);
                            values.put(InstanceColumns.JR_VERSION, jrVersion);
                            values.put(InstanceColumns.STATUS,
                                    instanceSyncFlag ? InstanceProviderAPI.STATUS_COMPLETE
                                            : InstanceProviderAPI.STATUS_INCOMPLETE);
                            values.put(InstanceColumns.CAN_EDIT_WHEN_COMPLETE, Boolean.toString(true));
                            // save the new instance object

                            instancesDao.saveInstance(values);
                            counter++;

                            encryptInstanceIfNeeded(formCursor, candidateInstance, values, instancesDao);
                        }
                    } catch (IOException | EncryptionException e) {
                        Timber.w(e);
                    } finally {
                        if (formCursor != null) {
                            formCursor.close();
                        }
                    }
                }
            }
            if (counter > 0) {
                currentStatus += String.format(Collect.getInstance().getString(R.string.instance_scan_count),
                        counter);
            }
        }
    } finally {
        Timber.i("[%d] doInBackground ends!", instance);
    }
    return currentStatus;
}

From source file:com.visva.voicerecorder.view.fragments.FragmentContact.java

private void editThisContact(int selectedPosition) {
    final Cursor cursor = mAdapter.getCursor();
    if (cursor == null)
        return;/*  ww w.  j a va  2  s .com*/
    cursor.moveToPosition(selectedPosition);

    final Uri uri = Contacts.getLookupUri(cursor.getLong(ContactsQuery.ID),
            cursor.getString(ContactsQuery.LOOKUP_KEY));

    // Standard system edit contact intent
    Intent intent = new Intent(Intent.ACTION_EDIT, uri);

    intent.putExtra("finishActivityOnSaveCompleted", true);

    // Start the edit activity
    startActivity(intent);
}

From source file:com.silentcircle.contacts.list.PhoneNumberListAdapter.java

@Override
protected void bindView(View itemView, int partition, Cursor cursor, int position) {
    ContactListItemView view = (ContactListItemView) itemView;

    view.setHighlightedPrefix(isSearchMode() ? getUpperCaseQueryString() : null);

    // Look at elements before and after this position, checking if contact IDs are same.
    // If they have one same contact ID, it means they can be grouped.
    ////w  ww  .  ja v  a 2  s . c om
    // In one group, only the first entry will show its photo and its name, and the other
    // entries in the group show just their data (e.g. phone number, email address).
    cursor.moveToPosition(position);
    boolean isFirstEntry = true;
    boolean showBottomDivider = true;
    final long currentContactId = cursor.getLong(PhoneQuery.PHONE_CONTACT_ID);
    if (cursor.moveToPrevious() && !cursor.isBeforeFirst()) {
        final long previousContactId = cursor.getLong(PhoneQuery.PHONE_CONTACT_ID);
        if (currentContactId == previousContactId) {
            isFirstEntry = false;
        }
    }
    cursor.moveToPosition(position);
    if (cursor.moveToNext() && !cursor.isAfterLast()) {
        final long nextContactId = cursor.getLong(PhoneQuery.PHONE_CONTACT_ID);
        if (currentContactId == nextContactId) {
            // The following entry should be in the same group, which means we don't want a
            // divider between them.
            // TODO: we want a different divider than the divider between groups. Just hiding
            // this divider won't be enough.
            showBottomDivider = false;
        }
    }
    cursor.moveToPosition(position);

    bindSectionHeaderAndDivider(view, position);
    if (isFirstEntry) {
        bindName(view, cursor);
        if (isQuickContactEnabled()) {
            // No need for photo uri here, because we can not have directory results. If we
            // ever do, we need to add photo uri to the query
            bindQuickContact(view, partition, cursor, PhoneQuery.PHONE_PHOTO_ID, -1,
                    PhoneQuery.PHONE_CONTACT_ID);
        } else {
            bindPhoto(view, cursor);
        }
    } else {
        unbindName(view);

        view.removePhotoView(true, false);
    }
    bindPhoneNumber(view, cursor);
    view.setDividerVisible(showBottomDivider);
}