Example usage for android.database Cursor getColumnIndexOrThrow

List of usage examples for android.database Cursor getColumnIndexOrThrow

Introduction

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

Prototype

int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException;

Source Link

Document

Returns the zero-based index for the given column name, or throws IllegalArgumentException if the column doesn't exist.

Usage

From source file:com.Beat.RingdroidEditActivity.java

private String getFilenameFromUri(Uri uri) {
    Cursor c = managedQuery(uri, null, "", null, null);
    if (c.getCount() == 0) {
        return null;
    }/*  ww  w .  j ava2s.  com*/
    c.moveToFirst();
    int dataIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);

    return c.getString(dataIndex);
}

From source file:com.android.calendar.event.EditEventView.java

private int findDefaultCalendarPosition(Cursor calendarsCursor) {
    if (calendarsCursor.getCount() <= 0) {
        return -1;
    }//from   ww w. j  a va  2 s .co m

    String defaultCalendar = Utils.getSharedPreference(mActivity, GeneralPreferences.KEY_DEFAULT_CALENDAR,
            (String) null);

    int calendarsOwnerIndex = calendarsCursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT);
    int accountNameIndex = calendarsCursor.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME);
    int accountTypeIndex = calendarsCursor.getColumnIndexOrThrow(Calendars.ACCOUNT_TYPE);
    int position = 0;
    calendarsCursor.moveToPosition(-1);
    while (calendarsCursor.moveToNext()) {
        String calendarOwner = calendarsCursor.getString(calendarsOwnerIndex);
        if (defaultCalendar == null) {
            // There is no stored default upon the first time running. Use a
            // primary
            // calendar in this case.
            if (calendarOwner != null && calendarOwner.equals(calendarsCursor.getString(accountNameIndex))
                    && !CalendarContract.ACCOUNT_TYPE_LOCAL
                            .equals(calendarsCursor.getString(accountTypeIndex))) {
                return position;
            }
        } else if (defaultCalendar.equals(calendarOwner)) {
            // Found the default calendar.
            return position;
        }
        position++;
    }
    return 0;
}

From source file:com.chaqianma.jd.fragment.PersonalAssetsFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
        case REQUEST_SDK_IMGS:
            if (data != null && data.getData() != null) {
                Uri imgUri = data.getData();
                ContentResolver resolver = getActivity().getContentResolver();
                String[] pojo = { MediaStore.Images.Media.DATA };
                Cursor cursor = null;
                try {
                    cursor = resolver.query(imgUri, pojo, null, null, null);
                    if (cursor != null && cursor.getCount() > 0) {
                        int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        cursor.moveToFirst();
                        new Thread(new BaseFragment.ImgRunable(cursor.getString(colunm_index), fileType,
                                selIdxTag, new UpdateUIHandler())).start();
                        //mHandler.post(new ImgRunable(cursor.getString(colunm_index)));
                    } else {
                        JDToast.showLongText(getActivity(), "");
                    }//from  w  w  w.  j a  va 2s  . co  m
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            }
            break;
        case REQUEST_TAKE_PHOTO:
            // mHandler.post(mRunnable);
            new Thread(
                    new BaseFragment.ImgRunable(Constants.TEMPPATH, fileType, selIdxTag, new UpdateUIHandler()))
                            .start();
            break;
        default:
            break;
        }
    }
}

From source file:com.fullteem.yueba.app.ui.ChatActivity.java

/**
 * ??//w w w . j  a va2  s .  c om
 * 
 * @param uri
 */
private void sendFile(Uri uri) {
    String filePath = null;
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(column_index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        filePath = uri.getPath();
    }
    File file = new File(filePath);
    if (file == null || !file.exists()) {
        Toast.makeText(getApplicationContext(), "?", 0).show();
        return;
    }
    if (file.length() > 10 * 1024 * 1024) {
        Toast.makeText(getApplicationContext(), "?10M", 0).show();
        return;
    }

    // ?
    EMMessage message = EMMessage.createSendMessage(EMMessage.Type.FILE);
    // ?chattype,??
    if (chatType == CHATTYPE_GROUP)
        message.setChatType(ChatType.GroupChat);

    message.setReceipt(toChatUsername);
    // add message body
    NormalFileMessageBody body = new NormalFileMessageBody(new File(filePath));
    message.addBody(body);
    conversation.addMessage(message);
    listView.setAdapter(adapter);
    adapter.refresh();
    listView.setSelection(listView.getCount() - 1);
    setResult(RESULT_OK);
}

From source file:com.android.calendar.event.CreateEventDialogFragment.java

private void setDefaultCalendarView(Cursor cursor) {
    if (cursor == null || cursor.getCount() == 0) {
        // Create an error message for the user that, when clicked,
        // will exit this activity without saving the event.
        dismiss();//ww  w.  j  av  a 2s .c o m
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.no_syncable_calendars).setIconAttribute(android.R.attr.alertDialogIcon)
                .setMessage(R.string.no_calendars_found)
                .setPositiveButton(R.string.add_account, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final Activity activity = getActivity();
                        if (activity != null) {
                            Intent nextIntent = new Intent(Settings.ACTION_ADD_ACCOUNT);
                            final String[] array = { "com.android.calendar" };
                            nextIntent.putExtra(Settings.EXTRA_AUTHORITIES, array);
                            nextIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                            activity.startActivity(nextIntent);
                        }
                    }
                }).setNegativeButton(android.R.string.no, null);
        builder.show();
        return;
    }

    String defaultCalendar = null;
    final Activity activity = getActivity();
    if (activity != null) {
        defaultCalendar = Utils.getSharedPreference(activity, GeneralPreferences.KEY_DEFAULT_CALENDAR,
                (String) null);
    } else {
        Log.e(TAG, "Activity is null, cannot load default calendar");
    }

    int calendarOwnerIndex = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT);
    int accountNameIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME);
    int accountTypeIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_TYPE);

    cursor.moveToPosition(-1);
    while (cursor.moveToNext()) {
        String calendarOwner = cursor.getString(calendarOwnerIndex);
        if (defaultCalendar == null) {
            // There is no stored default upon the first time running.  Use a primary
            // calendar in this case.
            if (calendarOwner != null && calendarOwner.equals(cursor.getString(accountNameIndex))
                    && !CalendarContract.ACCOUNT_TYPE_LOCAL.equals(cursor.getString(accountTypeIndex))) {
                setCalendarFields(cursor);
                return;
            }
        } else if (defaultCalendar.equals(calendarOwner)) {
            // Found the default calendar.
            setCalendarFields(cursor);
            return;
        }
    }
    cursor.moveToFirst();
    setCalendarFields(cursor);
}

From source file:com.android.calendar.event.EditEventView.java

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // This is only used for the Calendar spinner in new events, and only
    // fires when the
    // calendar selection changes or on screen rotation
    Cursor c = (Cursor) parent.getItemAtPosition(position);
    if (c == null) {
        // TODO: can this happen? should we drop this check?
        Log.w(TAG, "Cursor not set on calendar item");
        return;/*from   www . j  a v a 2s.  c  o m*/
    }

    // Do nothing if the selection didn't change so that reminders will not
    // get lost
    int idColumn = c.getColumnIndexOrThrow(Calendars._ID);
    long calendarId = c.getLong(idColumn);
    int colorColumn = c.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR);
    int color = c.getInt(colorColumn);
    int displayColor = Utils.getDisplayColorFromColor(color);

    // Prevents resetting of data (reminders, etc.) on orientation change.
    if (calendarId == mModel.mCalendarId && mModel.isCalendarColorInitialized()
            && displayColor == mModel.getCalendarColor()) {
        return;
    }

    setSpinnerBackgroundColor(displayColor);

    mModel.mCalendarId = calendarId;
    mModel.setCalendarColor(displayColor);
    mModel.mCalendarAccountName = c.getString(EditEventHelper.CALENDARS_INDEX_ACCOUNT_NAME);
    mModel.mCalendarAccountType = c.getString(EditEventHelper.CALENDARS_INDEX_ACCOUNT_TYPE);
    mModel.setEventColor(mModel.getCalendarColor());

    setColorPickerButtonStates(mModel.getCalendarEventColors());

    // Update the max/allowed reminders with the new calendar properties.
    int maxRemindersColumn = c.getColumnIndexOrThrow(Calendars.MAX_REMINDERS);
    mModel.mCalendarMaxReminders = c.getInt(maxRemindersColumn);
    int allowedRemindersColumn = c.getColumnIndexOrThrow(Calendars.ALLOWED_REMINDERS);
    mModel.mCalendarAllowedReminders = c.getString(allowedRemindersColumn);
    int allowedAttendeeTypesColumn = c.getColumnIndexOrThrow(Calendars.ALLOWED_ATTENDEE_TYPES);
    mModel.mCalendarAllowedAttendeeTypes = c.getString(allowedAttendeeTypesColumn);
    int allowedAvailabilityColumn = c.getColumnIndexOrThrow(Calendars.ALLOWED_AVAILABILITY);
    mModel.mCalendarAllowedAvailability = c.getString(allowedAvailabilityColumn);

    // Discard the current reminders and replace them with the model's
    // default reminder set.
    // We could attempt to save & restore the reminders that have been
    // added, but that's
    // probably more trouble than it's worth.
    mModel.mReminders.clear();
    mModel.mReminders.addAll(mModel.mDefaultReminders);
    mModel.mHasAlarm = mModel.mReminders.size() != 0;

    // Update the UI elements.
    mReminderItems.clear();
    LinearLayout reminderLayout = (LinearLayout) mScrollView.findViewById(R.id.reminder_items_container);
    reminderLayout.removeAllViews();
    prepareReminders();
    prepareAvailability();
}

From source file:com.fvd.nimbus.PaintActivity.java

private String getImagePath() {

    String[] projection = { MediaStore.Images.Thumbnails._ID, // The columns we want
            MediaStore.Images.Thumbnails.IMAGE_ID, MediaStore.Images.Thumbnails.KIND,
            MediaStore.Images.Thumbnails.DATA };
    String selection = MediaStore.Images.Thumbnails.KIND + "=" + // Select only mini's
            MediaStore.Images.Thumbnails.MINI_KIND;

    String sort = MediaStore.Images.Thumbnails._ID + " DESC";

    //At the moment, this is a bit of a hack, as I'm returning ALL images, and just taking the latest one. There is a better way to narrow this down I think with a WHERE clause which is currently the selection variable
    Cursor myCursor = this.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection,
            selection, null, sort);//  w ww  .  j  a  v  a2  s  . com

    long imageId = 0l;
    long thumbnailImageId = 0l;
    String thumbnailPath = "";

    try {
        myCursor.moveToFirst();
        imageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
        thumbnailImageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
        thumbnailPath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
    } finally {
        myCursor.close();
    }

    //Create new Cursor to obtain the file Path for the large image

    String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA };

    String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
    myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null,
            largeFileSort);
    String largeImagePath = "";

    try {
        myCursor.moveToFirst();

        largeImagePath = myCursor
                .getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
    } finally {
        myCursor.close();
    }
    // These are the two URI's you'll be interested in. They give you a handle to the actual images
    Uri uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            String.valueOf(imageId));
    Uri uriThumbnailImage = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
            String.valueOf(thumbnailImageId));

    if (largeImagePath.length() > 0)
        return largeImagePath;
    else if (uriLargeImage != null)
        return uriLargeImage.getPath();
    else if (uriThumbnailImage != null)
        return uriThumbnailImage.getPath();
    else
        return "";

}

From source file:com.ringdroid.RingdroidEditActivity.java

@Override
protected Dialog onCreateDialog(int id) {
    if (id == DIALOG_USE_ALL) {
        return new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle(R.string.ring_picker_title)
                .setSingleChoiceItems(R.array.set_ring_option, 0, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        ring_button_type = whichButton;
                    }/*ww  w  .  j a va  2  s  . co m*/
                }).setPositiveButton(R.string.alert_ok_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        int ring_type = 0;
                        if (ring_button_type == 3) {
                            Intent intent = new Intent();
                            Uri currentFileUri = Uri.parse(mFilename);
                            intent.setData(currentFileUri);
                            intent.setClass(RingdroidEditActivity.this,
                                    com.ringdroid.ChooseContactActivity.class);
                            RingdroidEditActivity.this.startActivity(intent);
                            return;
                        } else if (ring_button_type == 0) {
                            ring_type = RingtoneManager.TYPE_RINGTONE;
                        } else if (ring_button_type == 1) {
                            ring_type = RingtoneManager.TYPE_NOTIFICATION;
                        } else if (ring_button_type == 2) {
                            ring_type = RingtoneManager.TYPE_ALARM;
                        }
                        // u = Const.mp3dir + ring.getString(Const.mp3);
                        Uri currentFileUri = null;
                        if (!mFilename.startsWith("content:")) {
                            String selection;
                            selection = MediaStore.Audio.Media.DATA + "=?";//+"='"+DatabaseUtils.sqlEscapeString(mFilename)+"'";
                            String[] selectionArgs = new String[1];
                            selectionArgs[0] = mFilename;

                            Uri head = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                            Cursor c = getExternalAudioCursor(selection, selectionArgs);
                            if (c == null || c.getCount() == 0) {
                                head = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
                                c = getInternalAudioCursor(selection, selectionArgs);
                            }
                            startManagingCursor(c);
                            if (c == null || c.getCount() == 0)
                                return;
                            c.moveToFirst();
                            String itemUri = head.toString() + "/"
                                    + c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                            currentFileUri = Uri.parse(itemUri);
                        } else {
                            currentFileUri = Uri.parse(mFilename);
                        }
                        RingtoneManager.setActualDefaultRingtoneUri(RingdroidEditActivity.this, ring_type,
                                currentFileUri);
                        Toast.makeText(RingdroidEditActivity.this,
                                "" + getResources().getStringArray(R.array.set_ring_option)[ring_button_type],
                                Toast.LENGTH_SHORT).show();
                    }
                }).setNegativeButton(R.string.alertdialog_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                }).create();
    }
    return super.onCreateDialog(id);
}

From source file:com.vegnab.vegnab.MainVNActivity.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor finishedCursor) {
    mRowCt = finishedCursor.getCount();/*  w  w w.ja v  a2s .  c om*/
    // there will be various loaders, switch them out here
    switch (loader.getId()) {
    case VNContract.Loaders.EXISTING_PH_CODES:
        mExistingPhCodes.clear();
        while (finishedCursor.moveToNext()) {
            mExistingPhCodes.put(
                    finishedCursor.getString(finishedCursor.getColumnIndexOrThrow("PlaceHolderCode")),
                    finishedCursor.getLong(finishedCursor.getColumnIndexOrThrow("_id")));
        }
        break;

    case VNContract.Loaders.EXISTING_SPP:
        // if there are species in the master list, record this is Preferences
        boolean hasSpp = false;
        while (finishedCursor.moveToNext()) { // should be just one record
            if (finishedCursor.getLong(finishedCursor.getColumnIndexOrThrow("Ct")) > 0) {
                hasSpp = true;
            }
        }
        SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor prefEditor;
        prefEditor = sharedPref.edit();
        prefEditor.putBoolean(Prefs.SPECIES_LIST_DOWNLOADED, hasSpp);
        prefEditor.commit();
        break;
    }
}

From source file:com.dwdesign.tweetings.util.Utils.java

public static ArrayList<Long> getStatusIdsInDatabase(final Context context, final Uri uri,
        final long account_id) {
    final ArrayList<Long> list = new ArrayList<Long>();
    if (context == null)
        return list;
    final ContentResolver resolver = context.getContentResolver();
    final String where = Statuses.ACCOUNT_ID + " = " + account_id;
    final String[] projection = new String[] { Statuses.STATUS_ID };
    final Cursor cur = resolver.query(uri, projection, where, null, null);
    if (cur != null) {
        final int idx = cur.getColumnIndexOrThrow(Statuses.STATUS_ID);
        cur.moveToFirst();//from  ww w .  j  a v  a 2s  .  com
        while (!cur.isAfterLast()) {
            list.add(cur.getLong(idx));
            cur.moveToNext();
        }
        cur.close();
    }
    return list;
}