Example usage for android.database Cursor getInt

List of usage examples for android.database Cursor getInt

Introduction

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

Prototype

int getInt(int columnIndex);

Source Link

Document

Returns the value of the requested column as an int.

Usage

From source file:edu.pdx.cecs.orcycle.NoteUploader.java

private JSONArray getNoteResponsesJSON(long noteId) throws JSONException {

    // Create a JSON array to hold all of the answers
    JSONArray jsonAnswers = new JSONArray();

    mDb.openReadOnly();//from  w w w.  j ava 2 s  .c  o  m
    try {
        Cursor answers = mDb.fetchNoteAnswers(noteId);

        int questionId = answers.getColumnIndex(DbAdapter.K_NOTE_ANSWER_QUESTION_ID);
        int answerId = answers.getColumnIndex(DbAdapter.K_NOTE_ANSWER_ANSWER_ID);
        int otherText = answers.getColumnIndex(DbAdapter.K_NOTE_ANSWER_OTHER_TEXT);
        String text;

        // Cycle thru the database entries
        while (!answers.isAfterLast()) {

            // For each row, construct a JSON object
            JSONObject json = new JSONObject();

            try {
                // Place values into the JSON object
                json.put(FID_QUESTION_ID, answers.getInt(questionId));
                json.put(FID_ANSWER_ID, answers.getInt(answerId));

                if (null != (text = answers.getString(otherText))) {
                    text = text.trim();
                    if (!text.equals("")) {
                        json.put(FID_ANSWER_OTHER_TEXT, text);
                    }
                }
                // Place JSON objects into the JSON array
                jsonAnswers.put(json);
            } catch (Exception ex) {
                Log.e(MODULE_TAG, ex.getMessage());
            }
            // Move to next row
            answers.moveToNext();
        }
        answers.close();
    } catch (Exception ex) {
        Log.e(MODULE_TAG, ex.getMessage());
    } finally {
        mDb.close();
    }
    return jsonAnswers;
}

From source file:com.navjagpal.fileshare.WebServer.java

private void addFileEntity(final Uri uri, HttpResponse response) throws IOException {
    if (mTransferStartedListener != null) {
        mTransferStartedListener.started(uri);
    }/*from w w  w  .  j  a  v a2s  .  c  o m*/

    Cursor c = mContext.getContentResolver().query(uri, null, null, null, null);
    c.moveToFirst();
    int nameIndex = c.getColumnIndexOrThrow(FileSharingProvider.Files.Columns.DISPLAY_NAME);
    String name = c.getString(nameIndex);
    int dataIndex = c.getColumnIndexOrThrow(FileSharingProvider.Files.Columns._DATA);
    Uri data = Uri.parse(c.getString(dataIndex));

    c = mContext.getContentResolver().query(data, null, null, null, null);
    c.moveToFirst();
    int sizeIndex = c.getColumnIndexOrThrow(OpenableColumns.SIZE);
    int sizeBytes = c.getInt(sizeIndex);
    c.close();

    InputStream input = mContext.getContentResolver().openInputStream(data);

    String contentType = "application/octet-stream";
    if (name.endsWith(".jpg")) {
        contentType = "image/jpg";
    }

    response.addHeader("Content-Type", contentType);
    response.addHeader("Content-Length", "" + sizeBytes);
    response.setEntity(new InputStreamEntity(input, sizeBytes));
}

From source file:com.android.dialer.calllog.ContactInfoHelper.java

/**
 * Looks up a contact using the given URI.
 * <p>//w w  w .j  a  v  a  2  s  . c  o m
 * It returns null if an error occurs, {@link ContactInfo#EMPTY} if no matching contact is
 * found, or the {@link ContactInfo} for the given contact.
 * <p>
 * The {@link ContactInfo#formattedNumber} field is always set to {@code null} in the returned
 * value.
 */
private ContactInfo lookupContactFromUri(Uri uri) {
    if (uri == null) {
        return null;
    }
    if (!PermissionsUtil.hasContactsPermissions(mContext)) {
        return ContactInfo.EMPTY;
    }
    final ContactInfo info;
    Cursor phonesCursor = mContext.getContentResolver().query(uri, PhoneQuery._PROJECTION, null, null, null);

    if (phonesCursor != null) {
        try {
            if (phonesCursor.moveToFirst()) {
                info = new ContactInfo();
                long contactId = phonesCursor.getLong(PhoneQuery.PERSON_ID);
                String lookupKey = phonesCursor.getString(PhoneQuery.LOOKUP_KEY);
                info.lookupKey = lookupKey;
                info.lookupUri = Contacts.getLookupUri(contactId, lookupKey);
                info.name = phonesCursor.getString(PhoneQuery.NAME);
                info.type = phonesCursor.getInt(PhoneQuery.PHONE_TYPE);
                info.label = phonesCursor.getString(PhoneQuery.LABEL);
                info.number = phonesCursor.getString(PhoneQuery.MATCHED_NUMBER);
                info.normalizedNumber = phonesCursor.getString(PhoneQuery.NORMALIZED_NUMBER);
                info.photoId = phonesCursor.getLong(PhoneQuery.PHOTO_ID);
                info.photoUri = UriUtils.parseUriOrNull(phonesCursor.getString(PhoneQuery.PHOTO_URI));
                info.formattedNumber = null;
            } else {
                info = ContactInfo.EMPTY;
            }
        } finally {
            phonesCursor.close();
        }
    } else {
        // Failed to fetch the data, ignore this request.
        info = null;
    }
    return info;
}

From source file:se.kth.ssvl.tslab.bytewalla.androiddtn.servlib.storage.SQLiteImplementation.java

/**
 * Get multiple record from database based on condition.
 * @param table Name of table in which record already exist
 * @param condition Get records where this condition matches
 * @param field Only get this field from resulted row
 * @return If found then return the list of required field values otherwise return -1
 *//*from  ww w.jav a  2 s . c om*/
public int get_Bundles(String table, String condition, String orderBy, String limit) {

    try {

        Cursor cursor = db.query(table, null, condition, null, null, null, orderBy, limit);

        int fieldColumn = cursor.getColumnIndex("id");
        ArrayList<Bundle> bundles = new ArrayList<>();
        if (cursor != null) {
            cursor.moveToFirst();
            while (cursor.moveToNext()) {
                Bundle bundle = new Bundle(null);

                int id = cursor.getInt(fieldColumn);
                String source = cursor.getString(fieldColumn);
                String dest = cursor.getString(fieldColumn);
                int life = cursor.getInt(fieldColumn);
                bundle.source().assign(source);
                bundle.dest().assign(dest);
                bundle.creation_ts().set_seconds(life);
                bundle.set_bundleid(id);
                bundles.add(bundle);

            }
            cursor.close();
        } else {
            Log.d(TAG, "Row not found!");
        }
        cursor.close();
    } catch (IndexOutOfBoundsException e) {
        Log.e(TAG, "Id Already deleted");
    } catch (SQLiteException e) {
        Log.e(TAG, "Coundn't run the query");
    } catch (Exception e) {
        Log.e(TAG, "General Exception");
    }
    return -1;
}

From source file:com.money.manager.ex.reports.IncomeVsExpensesListFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    switch (loader.getId()) {
    case ID_LOADER_REPORT:
        //                ((IncomeVsExpensesAdapter) getListAdapter()).swapCursor(data);
        ((IncomeVsExpensesAdapter) getListAdapter()).changeCursor(data);

        if (isResumed()) {
            setListShown(true);//from w  w w.  j av  a  2  s .c  om
        } else {
            setListShownNoAnimation(true);
        }
        // calculate income, expenses
        double income = 0, expenses = 0;
        if (data == null)
            return;

        while (data.moveToNext()) {
            if (data.getInt(data.getColumnIndex(
                    IncomeVsExpenseReportEntity.Month)) != IncomeVsExpensesActivity.SUBTOTAL_MONTH) {
                income += data.getDouble(data.getColumnIndex(IncomeVsExpenseReportEntity.Income));
                expenses += data.getDouble(data.getColumnIndex(IncomeVsExpenseReportEntity.Expenses));
            }
        }
        updateListViewFooter(mFooterListView, income, expenses);
        if (data.getCount() > 0) {
            getListView().removeFooterView(mFooterListView);
            getListView().addFooterView(mFooterListView);
        }

        if (((IncomeVsExpensesActivity) getActivity()).mIsDualPanel) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    showChart();
                }
            }, 1 * 1000);
        }
        break;

    case ID_LOADER_YEARS:
        if (data != null && data.moveToFirst()) {
            while (!data.isAfterLast()) {
                int year = data.getInt(data.getColumnIndex("Year"));
                if (mYearsSelected.get(year, false) == false) {
                    mYearsSelected.put(year, false);
                }
                data.moveToNext();
            }
            startLoader();
        }
    }
}

From source file:com.samknows.measurement.storage.DBHelper.java

private JSONObject cursorTestResultToJSONObject(Cursor c) {
    JSONObject ret = new JSONObject();
    try {//from  ww  w .  ja v a2 s  .c o  m
        ret.put(SKSQLiteHelper.TR_COLUMN_ID, c.getLong(0));
        ret.put(SKSQLiteHelper.TR_COLUMN_TYPE, c.getString(1));
        ret.put(SKSQLiteHelper.TR_COLUMN_DTIME, c.getLong(2));
        ret.put(SKSQLiteHelper.TR_COLUMN_LOCATION, c.getString(3));
        ret.put(SKSQLiteHelper.TR_COLUMN_SUCCESS, c.getInt(4));
        ret.put(SKSQLiteHelper.TR_COLUMN_RESULT, c.getDouble(5));
        ret.put(SKSQLiteHelper.TR_COLUMN_BATCH_ID, c.getLong(6));
    } catch (JSONException je) {

    }
    return ret;
}

From source file:fr.unix_experience.owncloud_sms.engine.SmsFetcher.java

private void bufferizeMailboxMessages(MailboxID mbID) {
    String mbURI = mapMailboxIDToURI(mbID);

    if (_context == null || mbURI == null) {
        return;//from w  w w . java  2 s  .  co m
    }

    if (mbID != MailboxID.INBOX && mbID != MailboxID.SENT && mbID != MailboxID.DRAFTS) {
        Log.e(TAG, "Unhandled MailboxID " + mbID.ordinal());
        return;
    }

    // We generate a ID list for this message box
    String existingIDs = buildExistingMessagesString(mbID);

    Cursor c = null;
    if (existingIDs.length() > 0) {
        c = (new SmsDataProvider(_context)).query(mbURI, "_id NOT IN (" + existingIDs + ")");
    } else {
        c = (new SmsDataProvider(_context)).query(mbURI);
    }

    // Reading mailbox
    if (c != null && c.getCount() > 0) {
        c.moveToFirst();
        do {
            JSONObject entry = new JSONObject();

            try {
                for (int idx = 0; idx < c.getColumnCount(); idx++) {
                    String colName = c.getColumnName(idx);

                    // Id column is must be an integer
                    if (colName.equals(new String("_id")) || colName.equals(new String("type"))) {
                        entry.put(colName, c.getInt(idx));

                        // bufferize Id for future use
                        if (colName.equals(new String("_id"))) {
                        }
                    }
                    // Seen and read must be pseudo boolean
                    else if (colName.equals(new String("read")) || colName.equals(new String("seen"))) {
                        entry.put(colName, c.getInt(idx) > 0 ? "true" : "false");
                    } else {
                        // Special case for date, we need to record last without searching
                        if (colName.equals(new String("date"))) {
                            final Long tmpDate = c.getLong(idx);
                            if (tmpDate > _lastMsgDate) {
                                _lastMsgDate = tmpDate;
                            }
                        }
                        entry.put(colName, c.getString(idx));
                    }
                }

                // Mailbox ID is required by server
                entry.put("mbox", mbID.ordinal());

                _jsonDataDump.put(entry);

            } catch (JSONException e) {
                Log.e(TAG, "JSON Exception when reading SMS Mailbox", e);
                c.close();
            }
        } while (c.moveToNext());

        Log.d(TAG, c.getCount() + " messages read from " + mbURI);

        c.close();
    }
}

From source file:com.hybris.mobile.lib.commerce.provider.CatalogProvider.java

/**
 * Insert/Update the out-of-date sync status for an element (data or group) and return true if the sync adapter needs
 * to be triggered//from   w  w w.  j a va 2s .  c  o  m
 *
 * @param uriElement String of characters used to identify a name of a resource
 * @param idName     Unique name string
 * @param tableName  an element (data or group)
 * @param idElement  Unique element Identifier
 * @return true if the sync adapter needs to be triggered
 */
private boolean updateTrackSyncStatus(Uri uriElement, String idName, String tableName, String idElement) {

    boolean triggerSyncAdapter = true;

    ContentValues contentValues = new ContentValues();
    contentValues.put(idName, idElement);
    contentValues.put(CatalogContract.DataBaseSyncStatusGroup.ATT_STATUS, SyncStatus.OUTOFDATE.getValue());

    // Cursor to check if we need to trigger the sync adapter (data out-of-date)
    Cursor cursorCheckUpToDate = mDatabaseHelper.getReadableDatabase().query(tableName,
            new String[] { CatalogContract.DataBaseData.ATT_STATUS }, idName + "=?", new String[] { idElement },
            null, null, null);

    // Checking if we need to trigger the sync adapter
    if (cursorCheckUpToDate != null && cursorCheckUpToDate.getCount() > 0) {
        cursorCheckUpToDate.moveToFirst();

        // Sync status flag to out-of-date
        triggerSyncAdapter = (cursorCheckUpToDate.getInt(0) == SyncStatus.OUTOFDATE.getValue());

        cursorCheckUpToDate.close();
    }

    // Insert (or update) the row for the sync status out-to-date:
    // Case 1: we need to trigger the sync adapter
    // Case 2: the value is up-to-date, we invalidate the sync status for the next calls to the provider
    insert(Uri.withAppendedPath(uriElement, idElement), contentValues);

    return triggerSyncAdapter;
}

From source file:eu.operando.operandoapp.database.DatabaseHelper.java

public DomainFilter getDomainFilter(long id) {
    SQLiteDatabase db = this.getReadableDatabase();

    String selectQuery = "SELECT  * FROM " + TABLE_DOMAIN_FILTERS + " WHERE " + KEY_ID + " = " + id;

    Cursor c = db.rawQuery(selectQuery, null);

    if (c != null)
        c.moveToFirst();/*  w  ww.jav a2  s  .  c  o m*/

    DomainFilter domainFilter = new DomainFilter();
    domainFilter.setId(c.getInt(c.getColumnIndex(KEY_ID)));
    domainFilter.setContent((c.getString(c.getColumnIndex(KEY_CONTENT))));
    domainFilter.setSource((c.getString(c.getColumnIndex(KEY_SOURCE))));
    domainFilter.setModified(c.getString(c.getColumnIndex(KEY_MODIFIED)));
    domainFilter.setWildcard((c.getInt(c.getColumnIndex(KEY_WILDCARD))));

    return domainFilter;
}

From source file:no.nordicsemi.android.nrftoolbox.dfu.DfuActivity.java

@Override
public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) {
    if (data.moveToNext()) {
        /*//from w w  w  . ja v  a2s. c  o m
         * Here we have to check the column indexes by name as we have requested for all. The order may be different.
         */
        final String fileName = data
                .getString(data.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)/* 0 DISPLAY_NAME */);
        final int fileSize = data.getInt(data.getColumnIndex(MediaStore.MediaColumns.SIZE) /* 1 SIZE */);
        String filePath = null;
        final int dataIndex = data.getColumnIndex(MediaStore.MediaColumns.DATA);
        if (dataIndex != -1)
            filePath = data.getString(dataIndex /*2 DATA */);
        if (!TextUtils.isEmpty(filePath))
            mFilePath = filePath;

        mFileNameView.setText(fileName);
        mFileSizeView.setText(getString(R.string.dfu_file_size_text, fileSize));
        final boolean isHexFile = mStatusOk = MimeTypeMap.getFileExtensionFromUrl(fileName)
                .equalsIgnoreCase("HEX");
        mFileStatusView.setText(isHexFile ? R.string.dfu_file_status_ok : R.string.dfu_file_status_invalid);
        mUploadButton.setEnabled(mSelectedDevice != null && isHexFile);
    }
}