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.fordemobile.livepaintings.FragmentPagerSupport.java

/**
 * Reads the set of purchased items from the database in a background thread
 * and then adds those items to the set of owned items in the main UI
 * thread.//  www.j  a va 2 s  . c o m
 */
private void doInitializeOwnedItems() {
    Cursor cursor = this.mPurchaseDatabase.queryAllPurchasedItems();
    if (cursor == null) {
        return;
    }

    final Set<String> ownedItems = new HashSet<String>();
    try {
        int productIdCol = cursor.getColumnIndexOrThrow(PurchaseDatabase.PURCHASED_PRODUCT_ID_COL);
        while (cursor.moveToNext()) {
            String productId = cursor.getString(productIdCol);
            ownedItems.add(productId);
        }
    } finally {
        cursor.close();
    }

    // We will add the set of owned items in a new Runnable that runs on
    // the UI thread so that we don't need to synchronize access to
    // mOwnedItems.
    this.mHandler.post(new Runnable() {
        public void run() {
            FragmentPagerSupport.this.mOwnedItems.addAll(ownedItems);
            updateDisplay();
        }
    });
}

From source file:com.ezac.gliderlogs.FlightOnDutyActivity.java

private void fillData(Uri uri, String date) {

    String selection;//from  w  w w.  ja va2  s.c  o  m
    Cursor cursor;
    stringArrayList.clear();
    String[] projection = { GliderLogTables.D_DATE, GliderLogTables.D_PERIOD, GliderLogTables.D_P_NAME,
            GliderLogTables.D_DUTY, GliderLogTables.D_NAME };
    selection = GliderLogTables.R_DATE + " LIKE '" + date + "'";
    String sort = "" + GliderLogTables.D_PERIOD + " ASC";
    cursor = getContentResolver().query(uri, projection, selection, null, sort);
    if ((cursor != null) && (cursor.getCount() > 0)) {
        cursor.moveToFirst();
        do {
            stringArrayList.add(cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.D_PERIOD)));
            stringArrayList.add(cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.D_DUTY)));
            stringArrayList.add(cursor.getString(cursor.getColumnIndexOrThrow(GliderLogTables.D_NAME)));
            stringArrayList.add("");
        } while (cursor.moveToNext());
    }
    cursor.close();
}

From source file:com.odkclinic.client.PatientList.java

private void fillData() {
    // get cursor to list of patients
    Cursor patientCursor = mDb.getPatientList();
    startManagingCursor(patientCursor);/*from w w  w  .  j a  va 2s.c  om*/

    // cache group id
    mGroupIdColumnIndex = patientCursor.getColumnIndexOrThrow(PatientTable.ID.getName());

    Log.d(LOG_TAG, "There are " + patientCursor.getCount() + " patients.");

    // create listadapter for cursor
    mAdapter = new ExpandablePatientListAdapter(patientCursor, this, R.layout.patientlist_group_item,
            R.layout.patientlist_child_item,
            new String[] { PatientTable.NAME.getName(), PatientTable.ID.getName(),
                    CohortMemberTable.COHORT_ID.getName() },
            new int[] { R.id.patient_name, R.id.patient_id, R.id.cohort_id },
            new String[] { PatientTable.GENDER.getName(), PatientTable.RACE.getName(),
                    PatientTable.BIRTHDATE.getName() },
            new int[] { R.id.patientgender, R.id.patientrace, R.id.patientbirthdate });

    setListAdapter(mAdapter);
}

From source file:com.intel.xdk.contacts.Contacts.java

@SuppressWarnings("deprecation")
public void contactsChooserActivityResult(int requestCode, int resultCode, Intent intent) {

    if (resultCode == Activity.RESULT_OK) {
        Cursor cursor = activity.managedQuery(intent.getData(), null, null, null, null);
        cursor.moveToNext();/*from  ww w . java 2s .c om*/
        String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
        String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

        getAllContacts();
        String js = String.format(
                " var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.choose',true,true);e.success=true;e.contactid='%s';document.dispatchEvent(e);",
                contactId);
        injectJS("javascript:" + js);
        busy = false;
    } else {
        String js = "var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.choose',true,true);e.success=false;e.message='User canceled';document.dispatchEvent(e);";
        injectJS("javascript:" + js);
        busy = false;
    }

}

From source file:net.olejon.mdapp.NotesEditActivity.java

private void getNote() {
    if (noteId != 0) {
        SQLiteDatabase sqLiteDatabase = new NotesSQLiteHelper(mContext).getReadableDatabase();

        String[] queryColumns = { NotesSQLiteHelper.COLUMN_TITLE, NotesSQLiteHelper.COLUMN_TEXT,
                NotesSQLiteHelper.COLUMN_PATIENT_ID, NotesSQLiteHelper.COLUMN_PATIENT_NAME,
                NotesSQLiteHelper.COLUMN_PATIENT_DOCTOR, NotesSQLiteHelper.COLUMN_PATIENT_DEPARTMENT,
                NotesSQLiteHelper.COLUMN_PATIENT_ROOM, NotesSQLiteHelper.COLUMN_PATIENT_MEDICATIONS };
        Cursor cursor = sqLiteDatabase.query(NotesSQLiteHelper.TABLE, queryColumns,
                NotesSQLiteHelper.COLUMN_ID + " = " + noteId, null, null, null, null);

        if (cursor.moveToFirst()) {
            String title = cursor.getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_TITLE));
            String text = cursor.getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_TEXT));
            String patientId = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_ID));
            String patientName = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_NAME));
            String patientDoctor = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_DOCTOR));
            String patientDepartment = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_DEPARTMENT));
            String patientRoom = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_ROOM));
            String patientMedications = cursor
                    .getString(cursor.getColumnIndexOrThrow(NotesSQLiteHelper.COLUMN_PATIENT_MEDICATIONS));

            mTitleEditText.setText(title);
            mTextEditText.setText(text);
            mPatientIdEditText.setText(patientId);
            mPatientNameEditText.setText(patientName);
            mPatientDoctorEditText.setText(patientDoctor);
            mPatientDepartmentEditText.setText(patientDepartment);
            mPatientRoomEditText.setText(patientRoom);

            if (patientMedications != null && !patientMedications.equals("")) {
                try {
                    mPatientMedicationsJsonArray = new JSONArray(patientMedications);

                    getMedications();/*from w ww.j a v  a  2 s  .  c o m*/
                } catch (Exception e) {
                    Log.e("NotesEditActivity", Log.getStackTraceString(e));
                }
            }
        }

        cursor.close();
        sqLiteDatabase.close();
    }
}

From source file:com.demo.android.smsapp.activities.SMSHistoryActivity.java

private ArrayList<SMSModel> getMessages() {
    //time in long, type:1 inbox- type:2 sent
    ArrayList<SMSModel> smsModels = new ArrayList<>();
    Uri smsUri = Uri.parse("content://sms");
    String[] columns = new String[] { "_id", "address", "person", "date", "body", "type" };
    //String selection = "SELECT " + CallLog.Calls._ID + \" FROM calls WHERE type != \" + CallLog.Calls.VOICEMAIL_TYPE + \" GROUP BY \" + CallLog.Calls.NUMBER+\")\"";
    Cursor cursor = getContentResolver().query(smsUri, columns, null, null, null);//this.getContentResolver().query(Uri.parse( "content://sms/conversations?simple=true"), null, null, null, "normalized_date desc" );//
    cursor.moveToFirst();/*w  w  w  .  j a  v  a 2  s .co m*/
    Log.e("total:", cursor.getCount() + "");
    String id, address, body, person, type, date;

    for (int i = 0; i < cursor.getCount(); i++) {

        address = cursor.getString(cursor.getColumnIndex("address"));
        body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
        person = cursor.getString(cursor.getColumnIndex("person"));
        type = cursor.getString(cursor.getColumnIndex("type"));
        date = cursor.getString(cursor.getColumnIndexOrThrow("date"));
        id = cursor.getString(cursor.getColumnIndexOrThrow("_id"));

        smsModels.add(SMSModel.getSMSModelObject(id, address, body, type, date));

        Log.e("readSMS", "Number:" + address + ",Person:" + person + ",Message: " + body + ",type:" + type
                + ",date:" + date + ",id:" + id);

        cursor.moveToNext();
    }
    return smsModels;
}

From source file:sjizl.com.FileUploadTest.java

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();/*w w w .jav  a2 s .  c  o m*/
    return cursor.getString(column_index);
}

From source file:com.amazonaws.mobileconnectors.s3.transferutility.TransferService.java

/**
 * Loads transfers from database. These transfers are unfinished from
 * previous session or are new transfers waiting for network. It skips any
 * transfer that is already tracked by the status updater. Also starts
 * transfers whose states indicate running but aren't.
 *///from   ww w.  j ava2s  . c  o  m
void loadTransfersFromDB() {
    LOGGER.debug("Loading transfers from database");
    Cursor c = null;
    int count = 0;

    try {
        // Query for the unfinshed transfers
        c = dbUtil.queryTransfersWithTypeAndStates(TransferType.ANY, UNFINISHED_TRANSFER_STATES);
        while (c.moveToNext()) {
            final int id = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_ID));
            final TransferState state = TransferState
                    .getState(c.getString(c.getColumnIndexOrThrow(TransferTable.COLUMN_STATE)));
            final int partNumber = c.getInt(c.getColumnIndexOrThrow(TransferTable.COLUMN_PART_NUM));
            // add unfinished transfers
            if (partNumber == 0) {
                if (updater.getTransfer(id) == null) {
                    final TransferRecord transfer = new TransferRecord(id);
                    transfer.updateFromDB(c);
                    if (transfer.start(s3, dbUtil, updater, networkInfoReceiver)) {
                        updater.addTransfer(transfer);
                        count++;
                    }
                } else {
                    final TransferRecord transfer = updater.getTransfer(id);
                    if (!transfer.isRunning()) {
                        transfer.start(s3, dbUtil, updater, networkInfoReceiver);
                    }
                }
            }
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    LOGGER.debug(count + " transfers are loaded from database");
}

From source file:com.android.calendar.selectcalendars.SelectCalendarsSimpleAdapter.java

private void initData(Cursor c) {
    if (mCursor != null && c != mCursor) {
        mCursor.close();/*from   ww  w .  j a v a 2s . com*/
    }
    if (c == null) {
        mCursor = c;
        mRowCount = 0;
        mData = null;
        return;
    }
    // TODO create a broadcast listener for ACTION_PROVIDER_CHANGED to update the cursor
    mCursor = c;
    mIdColumn = c.getColumnIndexOrThrow(Calendars._ID);
    mNameColumn = c.getColumnIndexOrThrow(Calendars.CALENDAR_DISPLAY_NAME);
    mColorColumn = c.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR);
    mVisibleColumn = c.getColumnIndexOrThrow(Calendars.VISIBLE);
    mOwnerAccountColumn = c.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT);
    mAccountNameColumn = c.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME);
    mAccountTypeColumn = c.getColumnIndexOrThrow(Calendars.ACCOUNT_TYPE);

    mRowCount = c.getCount();
    mData = new CalendarRow[(c.getCount())];
    c.moveToPosition(-1);
    int p = 0;
    while (c.moveToNext()) {
        mData[p] = new CalendarRow();
        mData[p].id = c.getLong(mIdColumn);
        mData[p].displayName = c.getString(mNameColumn);
        mData[p].color = c.getInt(mColorColumn);
        mData[p].selected = c.getInt(mVisibleColumn) != 0;
        mData[p].ownerAccount = c.getString(mOwnerAccountColumn);
        mData[p].accountName = c.getString(mAccountNameColumn);
        mData[p].accountType = c.getString(mAccountTypeColumn);
        p++;
    }
}

From source file:com.github.gfx.android.orma.example.fragment.BenchmarkFragment.java

Single<Result> startSelectAllWithHandWritten() {
    return Single.fromCallable(() -> {
        long result = runWithBenchmark(() -> {
            AtomicInteger count = new AtomicInteger();

            Database db = hw.getReadableDatabase();
            Cursor cursor = db.query("todo", new String[] { "id, title, content, done, createdTime" }, null,
                    null, null, null, "createdTime ASC", null // whereClause, whereArgs, groupBy, having, orderBy, limit
            );//from  ww w .  j a v a2  s . c  om

            if (cursor.moveToFirst()) {
                int titleIndex = cursor.getColumnIndexOrThrow("title");
                int contentIndex = cursor.getColumnIndexOrThrow("content");
                int createdTimeIndex = cursor.getColumnIndexOrThrow("createdTime");
                do {
                    @SuppressWarnings("unused")
                    String title = cursor.getString(titleIndex);
                    @SuppressWarnings("unused")
                    String content = cursor.getString(contentIndex);
                    @SuppressWarnings("unused")
                    Date createdTime = new Date(cursor.getLong(createdTimeIndex));

                    count.incrementAndGet();
                } while (cursor.moveToNext());
            }
            cursor.close();

            long dbCount = longForQuery(db, "SELECT COUNT(*) FROM todo", null);
            if (dbCount != count.get()) {
                throw new AssertionError("unexpected get: " + count.get() + " != " + dbCount);
            }

            Log.d(TAG, "HandWritten/forEachAll count: " + count);
        });
        return new Result("HandWritten/forEachAll", result);
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}