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:gov.cdc.epiinfo.RecordList.java

private void editRecord(long id) {
    Cursor c = mDbHelper.fetchRecord(id);
    AppManager.SetCurrentDatabase(mDbHelper);

    c.moveToPosition(0);
    waitDialog = ProgressDialog.show(this, getString(R.string.loading_form), getString(R.string.please_wait),
            true);//  w  w w.  jav  a2  s.c om

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean useInterviewMode = sharedPref.getBoolean("interview", false) || formMetadata.IsInterviewForm;
    Intent i;
    if (useInterviewMode) {
        i = new Intent(this, Interviewer.class);
    } else {
        i = new Intent(this, RecordEditor.class);
    }

    i.putExtra(EpiDbHelper.KEY_ROWID, id);
    i.putExtra(EpiDbHelper.GUID, c.getString(c.getColumnIndexOrThrow(EpiDbHelper.GUID)));
    for (int x = 0; x < formMetadata.DataFields.size(); x++) {
        if (formMetadata.DataFields.get(x).getType().equals("10")
                || formMetadata.DataFields.get(x).getType().equals("11")
                || formMetadata.DataFields.get(x).getType().equals("12")
                || formMetadata.DataFields.get(x).getType().equals("18")
                || formMetadata.DataFields.get(x).getType().equals("19")) {
            String fieldName = formMetadata.DataFields.get(x).getName();
            int columnIndex = c.getColumnIndexOrThrow(fieldName);
            int value = c.getInt(columnIndex);
            i.putExtra(fieldName, value);
        } else if (formMetadata.DataFields.get(x).getType().equals("17")) {
            if (formMetadata.DataFields.get(x).getListValues().size() > 100) {
                String fieldName = formMetadata.DataFields.get(x).getName();
                int columnIndex = c.getColumnIndexOrThrow(fieldName);
                String value = c.getString(columnIndex);
                i.putExtra(fieldName, value);
            } else {
                String fieldName = formMetadata.DataFields.get(x).getName();
                int columnIndex = c.getColumnIndexOrThrow(fieldName);
                int value = c.getInt(columnIndex);
                i.putExtra(fieldName, value);
            }
        } else if (formMetadata.DataFields.get(x).getType().equals("5")) {
            String fieldName = formMetadata.DataFields.get(x).getName();
            int columnIndex = c.getColumnIndexOrThrow(fieldName);
            double value = c.getDouble(columnIndex);
            i.putExtra(fieldName, value);
        } else {
            String fieldName = formMetadata.DataFields.get(x).getName();
            int columnIndex = c.getColumnIndexOrThrow(fieldName);
            String value = c.getString(columnIndex);
            i.putExtra(fieldName, value);
        }
    }
    new PreCompiledLoader().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, i);
}

From source file:org.lastmilehealth.collect.android.tasks.BluetoothService.java

private void instancesProcessing() {
    //fill db with new values
    String dbpath = Collect.TMP_PATH + "/instances.db";
    SQLiteDatabase db = SQLiteDatabase.openDatabase(dbpath, null, SQLiteDatabase.OPEN_READONLY);
    Cursor cursor = db.query(InstanceProvider.INSTANCES_TABLE_NAME, null, null, null, null, null, null);
    Log.d("~", "cursor.getCount(): " + cursor.getCount());

    cursor.moveToPosition(-1);
    while (cursor.moveToNext()) {
        String newInstanceName = cursor
                .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.DISPLAY_NAME));
        String instanceFilePath = cursor
                .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.INSTANCE_FILE_PATH));
        String newFilePath;/*  w ww.j a va  2  s  .c  o m*/

        if (new File(instanceFilePath).exists()) { //instance with this path already exist, rare case but not impossible
            newFilePath = getInstanceFilePath(instanceFilePath, 1);
            Log.d(TAG, "instance already exists, new path: " + newFilePath);

            String num = newFilePath.substring(newFilePath.lastIndexOf("(") + 1, newFilePath.lastIndexOf(")"));
            newInstanceName += "(" + num + ")";
            //Log.d(TAG, "newInstanceName: "+newInstanceName);

            final String fromName = instanceFilePath.substring(instanceFilePath.lastIndexOf("instances/") + 10);
            final String toName = newFilePath.substring(instanceFilePath.lastIndexOf("instances/") + 10);

            //raname file in tmp folder to prepare for copy direcory
            try {
                Log.d(TAG, "rename " + fromName + " to " + toName);
                org.apache.commons.io.FileUtils.copyFile(new File(Collect.TMP_PATH, fromName),
                        new File(Collect.TMP_PATH, toName));
                org.apache.commons.io.FileUtils.deleteQuietly(new File(Collect.TMP_PATH, fromName));
            } catch (Exception e) {
            }
        } else {
            newFilePath = new File(Collect.INSTANCES_PATH,
                    instanceFilePath.substring(instanceFilePath.lastIndexOf("/"))).getAbsolutePath();
            Log.d(TAG, "not exist, new path " + newFilePath);
        }

        String submissionUri = null;
        if (!cursor.isNull(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.SUBMISSION_URI))) {
            submissionUri = cursor
                    .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.SUBMISSION_URI));
        }

        //add to db with new name, it it was duplicated
        ContentValues values = new ContentValues();
        values.put(InstanceProviderAPI.InstanceColumns.DISPLAY_NAME, newInstanceName);
        values.put(InstanceProviderAPI.InstanceColumns.SUBMISSION_URI, submissionUri);
        values.put(InstanceProviderAPI.InstanceColumns.INSTANCE_FILE_PATH, newFilePath);
        values.put(InstanceProviderAPI.InstanceColumns.JR_FORM_ID,
                cursor.getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.JR_FORM_ID)));
        values.put(InstanceProviderAPI.InstanceColumns.JR_VERSION,
                cursor.getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.JR_VERSION)));
        values.put(InstanceProviderAPI.InstanceColumns.STATUS,
                cursor.getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.STATUS)));
        values.put(InstanceProviderAPI.InstanceColumns.CAN_EDIT_WHEN_COMPLETE, cursor
                .getString(cursor.getColumnIndex(InstanceProviderAPI.InstanceColumns.CAN_EDIT_WHEN_COMPLETE)));

        Log.d(TAG, "insert new instance record: " + newInstanceName + " with path :" + newFilePath);
        Collect.getInstance().getContentResolver().insert(InstanceProviderAPI.InstanceColumns.CONTENT_URI,
                values);
    }
    cursor.close();
    db.close();

    //copy directory after deleting metadata, clear all temporary data
    org.apache.commons.io.FileUtils.deleteQuietly(new File(Collect.TMP_PATH, "instances.db"));
    org.apache.commons.io.FileUtils.deleteQuietly(new File(Collect.ZIP_PATH));
    try {
        org.apache.commons.io.FileUtils.copyDirectory(new File(Collect.TMP_PATH),
                new File(Collect.INSTANCES_PATH));
        org.apache.commons.io.FileUtils.deleteDirectory(new File(Collect.TMP_PATH));
    } catch (Exception e) {
    }
}

From source file:com.dilyar.weather.app.ForecastFragment.java

private void updateBackgroundView(Cursor cursor) {

    Log.d(LOG_TAG, mInputLocationName + " updateBackgroundView() called");

    if (cursor != null) {

        int imagesCount = cursor.getCount();
        if (imagesCount > 0) {
            if (Utility.isUpdatedManually(getActivity())) {
                Utility.setCurrentPhotoCursorIndex(getActivity(), mInputLocationName,
                        new Random().nextInt(imagesCount), true);
                Utility.setUpdatedManually(getActivity(), false);
            }/* www  . java 2 s  . co  m*/
            int index = Utility.getCurrentPhotoCursorIndex(getActivity(), mInputLocationName);
            if (cursor.moveToPosition(index)) {
                //TODO: Add Transition while changing new image
                String imageUrl = cursor.getString(COL_PHOTO_URL);
                ImageLoader.getInstance().loadImageWithUrl(imageUrl, mBackgroundImageview);

                Log.d(LOG_TAG, "image Url from updateBackgroundView(): " + imageUrl);
                Utility.setImageFillScreen(getActivity(), mBackgroundImageview);

                mBackgroundImageview.setColorFilter(getResources().getColor(R.color.background_filter),
                        PorterDuff.Mode.MULTIPLY);

                String imageOwner = cursor.getString(COL_PHOTO_OWNER);
                mImageOwnerTextview.setText(Utility.formatImageOwnerText(getActivity(), imageOwner));

            } else {
                Log.e(LOG_TAG, "Photo cursor cannot move to position: " + index);
            }
        }
    } else {
        Log.e(LOG_TAG, "UpdateBackgroundView() failed, photo cursor is null.");
    }

}

From source file:android.com.example.contactslist.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
    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  www . ja  v a2 s.c o m
}

From source file:net.simonvt.cathode.ui.fragment.ShowFragment.java

private void updateGenreViews(final Cursor cursor) {
    if (cursor.getCount() > 0) {
        StringBuilder sb = new StringBuilder();
        final int genreColumnIndex = cursor.getColumnIndex(ShowGenreColumns.GENRE);

        cursor.moveToPosition(-1);

        while (cursor.moveToNext()) {
            sb.append(cursor.getString(genreColumnIndex));
            if (!cursor.isLast())
                sb.append(", ");
        }/*from  w w  w . j  a  va2  s  .  c o m*/

        genres = sb.toString();
    } else {
        genres = null;
    }

    updateTitle();
}

From source file:com.wuman.androidimageloader.ImageLoader.java

/**
 * Pre-loads a range of images into memory from a {@link Cursor}.
 * <p>// www .j av  a 2 s  .c om
 * Typically, an {@link Activity} would register a {@link DataSetObserver}
 * and an {@link android.widget.AdapterView.OnItemSelectedListener}, then
 * call this method to prime the in-memory cache with images adjacent to the
 * current selection whenever the selection or data changes.
 * <p>
 * Any invalid positions in the specified range will be silently ignored.
 * 
 * @param cursor
 *            a {@link Cursor} containing the image URLs.
 * @param columnIndex
 *            the column index of the image URL. The column value may be
 *            {@code NULL}.
 * @param start
 *            the first position to load. For example,
 *            {@code selectedPosition - 5}.
 * @param end
 *            the first position not to load. For example,
 *            {@code selectedPosition + 5}.
 * @see #preload(String)
 */
public void preload(Cursor cursor, int columnIndex, int start, int end) {
    for (int position = start; position < end; position++) {
        if (cursor.moveToPosition(position)) {
            String url = cursor.getString(columnIndex);
            if (!TextUtils.isEmpty(url)) {
                preload(url);
            }
        }
    }
}

From source file:com.fitforbusiness.contact.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
    cursor.moveToPosition(position);

    Log.d("contactId", cursor.getString(ContactsQuery.ID));

    Intent intent = new Intent();
    intent.putExtra("contactId", cursor.getString(ContactsQuery.ID));
    getActivity().setResult(Activity.RESULT_OK, intent);
    getActivity().finish();/*from  w  w  w .j ava 2s  .  c om*/

    // 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.money.manager.ex.account.AccountTransactionListFragment.java

/**
 * Select the current account in the accounts dropdown.
 *///from  w  w w  .  ja va  2 s.c om
private void selectCurrentAccount() {
    Spinner spinner = getAccountsSpinner();
    if (spinner == null)
        return;

    // find account
    SimpleCursorAdapter adapter = (SimpleCursorAdapter) spinner.getAdapter();
    if (adapter == null)
        return;

    Cursor cursor = adapter.getCursor();
    int position = Constants.NOT_SET;

    for (int i = 0; i < adapter.getCount(); i++) {
        cursor.moveToPosition(i);
        String accountIdString = cursor.getString(cursor.getColumnIndex(Account.ACCOUNTID));
        int accountId = Integer.parseInt(accountIdString);
        if (accountId == mAccountId) {
            position = i;
            break;
        }
    }

    spinner.setSelection(position);
}

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

private void updateThisContactFavourite(int selectedPosition) {
    final Cursor cursor = mAdapter.getCursor();
    Resources res = getActivity().getResources();
    if (cursor == null)
        return;/* w  ww.j  a  va 2  s . co  m*/
    // Moves to the Cursor row corresponding to the ListView item that was clicked
    cursor.moveToPosition(selectedPosition);
    if (mSQLiteHelper == null) {
        mSQLiteHelper = MyCallRecorderApplication.getInstance().getSQLiteHelper(getActivity());
    }

    String contactId = cursor.getString(ContactsQuery.ID);
    if (StringUtility.isEmpty(contactId))
        return;

    ArrayList<String> phones = Utils.getContactUriTypeFromContactId(getActivity().getContentResolver(),
            contactId);
    String phoneNo = "";
    if (phones == null || phones.size() == 0) {
        phoneNo = "";
    } else
        phoneNo = phones.get(0);
    String phoneName = cursor.getString(ContactsQuery.DISPLAY_NAME);
    FavouriteItem favouriteItem = new FavouriteItem(phoneNo, phoneName, 1, contactId);
    if (Utils.isCheckFavouriteContact(getActivity(), contactId)) {
        String removedFavouriteContact = res.getString(R.string.removed_from_favourite, phoneName);
        mSQLiteHelper.deleteFavouriteItem(favouriteItem);
        Toast.makeText(getActivity(), removedFavouriteContact, Toast.LENGTH_SHORT).show();
    } else {
        String addFavouriteContact = res.getString(R.string.added_to_favourite, phoneName);
        mSQLiteHelper.addNewFavoriteItem(favouriteItem);
        Toast.makeText(getActivity(), addFavouriteContact, Toast.LENGTH_SHORT).show();
    }
    if (MyCallRecorderApplication.getInstance().getActivity() != null) {
        Utils.requestToRefreshView(MyCallRecorderApplication.getInstance().getActivity(),
                ActivityHome.FRAGMENT_ALL_RECORDING);
        Utils.requestToRefreshView(MyCallRecorderApplication.getInstance().getActivity(),
                ActivityHome.FRAGMENT_FAVOURITE);
    }
    mAdapter.notifyDataSetChanged();
}

From source file:com.polyvi.xface.extension.telephony.XTelephonyExt.java

/**
 * ?id?//www  . j  a v  a 2s  .  c o  m
 *
 * @param[in] callRecordType ?
 * @param[in] callRecordIndex ?
 * @return ?JSON
 */
private JSONObject getCallRecord(String callRecordType, int recordIndex) {
    int callType = getCallRecordType(callRecordType);
    Cursor c = mContentResolver.query(CallLog.Calls.CONTENT_URI,
            new String[] { CallLog.Calls.NUMBER, CallLog.Calls._ID, CallLog.Calls.CACHED_NAME,
                    CallLog.Calls.TYPE, CallLog.Calls.DATE, CallLog.Calls.DURATION },
            CallLog.Calls.TYPE + "=" + callType, null, CallLog.Calls.DEFAULT_SORT_ORDER);
    String callRecordAddress = "";
    String callRecordId = "";
    String callRecordName = "";
    long durationSeconds = 0;
    long startTime = 0;
    JSONObject callRecord = new JSONObject();
    if (null != c) {
        if (c.moveToPosition(recordIndex)) {
            callRecordAddress = c.getString(0);
            callRecordId = c.getString(1);
            callRecordName = c.getString(2);
            startTime = c.getLong(4);
            durationSeconds = c.getLong(5);
        }
        c.close();
        try {
            callRecord.put("callRecordAddress", callRecordAddress);
            callRecord.put("callRecordId", callRecordId);
            callRecord.put("callRecordName", callRecordName);
            callRecord.put("durationSeconds", durationSeconds);
            callRecord.put("startTime", startTime);
            callRecord.put("callRecordType", callRecordType);
        } catch (JSONException e) {
            XLog.e(CLASS_NAME, e.getMessage());
        }
    }
    return callRecord;
}