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:com.mail163.email.mail.transport.Rfc822Output.java

/**
 * Write the entire message to an output stream.  This method provides buffering, so it is
 * not necessary to pass in a buffered output stream here.
 *
 * @param context system context for accessing the provider
 * @param messageId the message to write out
 * @param out the output stream to write the message to
 * @param appendQuotedText whether or not to append quoted text if this is a reply/forward
 *
 * TODO alternative parts (e.g. text+html) are not supported here.
 *//*w w  w  . ja v a  2s . co m*/
public static void writeTo(Context context, long messageId, OutputStream out, boolean appendQuotedText,
        boolean sendBcc) throws IOException, MessagingException {
    Message message = Message.restoreMessageWithId(context, messageId);
    if (message == null) {
        // throw something?
        return;
    }

    OutputStream stream = new BufferedOutputStream(out, 1024);
    Writer writer = new OutputStreamWriter(stream);

    // Write the fixed headers.  Ordering is arbitrary (the legacy code iterated through a
    // hashmap here).

    String date = DATE_FORMAT.format(new Date(message.mTimeStamp));
    writeHeader(writer, "Date", date);

    writeEncodedHeader(writer, "Subject", message.mSubject);
    writeEncodedHeader(writer, "X-Priority", message.mPriority);
    writeHeader(writer, "Message-ID", message.mMessageId);

    writeAddressHeader(writer, "From", message.mFrom);
    writeAddressHeader(writer, "To", message.mTo);
    writeAddressHeader(writer, "Cc", message.mCc);
    // Address fields.  Note that we skip bcc unless the sendBcc argument is true
    // SMTP should NOT send bcc headers, but EAS must send it!
    if (sendBcc) {
        writeAddressHeader(writer, "Bcc", message.mBcc);
    }
    writeAddressHeader(writer, "Reply-To", message.mReplyTo);
    writeHeader(writer, "MIME-Version", "1.0");

    // Analyze message and determine if we have multiparts
    String text = buildBodyText(context, message, appendQuotedText);

    if (!Global.sendMessage.equals("")) {
        if (text.endsWith(Global.sendMessage)) {//
            text = text.substring(0, text.lastIndexOf(Global.sendMessage));
            text = text + Global.sendMessage;
        } else {
            text = text + "\n\n\n" + Global.sendMessage;
        }
    }
    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId);
    Cursor attachmentsCursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null,
            null, null);

    try {
        int attachmentCount = attachmentsCursor.getCount();
        boolean multipart = attachmentCount > 0;
        String multipartBoundary = null;
        String multipartType = "mixed";

        // Simplified case for no multipart - just emit text and be done.
        if (!multipart) {
            if (text != null) {
                writeTextWithHeaders(writer, stream, text);
            } else {
                writer.write("\r\n"); // a truly empty message
            }
        } else {
            // continue with multipart headers, then into multipart body
            multipartBoundary = "--_com.warmtel.yimail_" + System.nanoTime();

            // Move to the first attachment; this must succeed because multipart is true
            attachmentsCursor.moveToFirst();
            if (attachmentCount == 1) {
                // If we've got one attachment and it's an ics "attachment", we want to send
                // this as multipart/alternative instead of multipart/mixed
                int flags = attachmentsCursor.getInt(Attachment.CONTENT_FLAGS_COLUMN);
                if ((flags & Attachment.FLAG_ICS_ALTERNATIVE_PART) != 0) {
                    multipartType = "alternative";
                }
            }

            writeHeader(writer, "Content-Type",
                    "multipart/" + multipartType + "; boundary=\"" + multipartBoundary + "\"");
            // Finish headers and prepare for body section(s)
            writer.write("\r\n");

            // first multipart element is the body
            if (text != null) {
                writeBoundary(writer, multipartBoundary, false);
                writeTextWithHeaders(writer, stream, text);
            }

            // Write out the attachments until we run out
            do {
                writeBoundary(writer, multipartBoundary, false);
                Attachment attachment = Attachment.getContent(attachmentsCursor, Attachment.class);
                writeOneAttachment(context, writer, stream, attachment);
                writer.write("\r\n");
            } while (attachmentsCursor.moveToNext());

            // end of multipart section
            writeBoundary(writer, multipartBoundary, true);
        }
    } finally {
        attachmentsCursor.close();
    }

    writer.flush();
    out.flush();
}

From source file:com.nextgis.maplib.map.VectorLayer.java

@Override
public void fromJSON(JSONObject jsonObject) throws JSONException {
    super.fromJSON(jsonObject);
    mGeometryType = jsonObject.getInt(JSON_GEOMETRY_TYPE_KEY);
    mIsInitialized = jsonObject.getBoolean(JSON_IS_INITIALIZED_KEY);
    if (jsonObject.has(JSON_RENDERERPROPS_KEY)) {
        setDefaultRenderer();/*w w  w.jav a  2 s  .co  m*/

        if (null != mRenderer && mRenderer instanceof IJSONStore) {
            IJSONStore jsonStore = (IJSONStore) mRenderer;
            jsonStore.fromJSON(jsonObject.getJSONObject(JSON_RENDERERPROPS_KEY));
        }
    }

    if (mIsInitialized) {
        mExtents = new GeoEnvelope();

        //load vector cache
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        SQLiteDatabase db = map.getDatabase(false);
        String[] columns = new String[] { "_ID", "GEOM" };
        Cursor cursor = db.query(mPath.getName(), columns, null, null, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            mVectorCacheItems = new ArrayList<>();
            do {
                try {
                    GeoGeometry geoGeometry = GeoGeometry.fromBlob(cursor.getBlob(1));
                    int nId = cursor.getInt(0);
                    mExtents.merge(geoGeometry.getEnvelope());
                    mVectorCacheItems.add(new VectorCacheItem(geoGeometry, nId));
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } while (cursor.moveToNext());
        }
    }
}

From source file:totalcross.android.ConnectionManager4A.java

public static void setDefaultConfiguration(int type, String cfg) {
    if (cfg == null)
        cfg = "";

    switch (type) {
    case GPRS: {//from  ww  w  . j  av  a  2  s.  c om
        int id = -1;
        ContentResolver contentResolver = Launcher4A.loader.getContentResolver();
        Cursor cursor = contentResolver.query(CONTENT_URI, new String[] { "_id" },
                "apn = ? and user = ? and password = ?", new String[] { "tim.br", "tim", "tim" }, null);
        if (cursor == null || cursor.getCount() <= 0) {
            TelephonyManager tel = (TelephonyManager) Launcher4A.loader
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String networkOperator = tel.getNetworkOperator();

            if (networkOperator != null && networkOperator.length() > 0) {
                int mcc = Integer.parseInt(networkOperator.substring(0, 3));
                int mnc = Integer.parseInt(networkOperator.substring(3));
                ContentValues values = new ContentValues();
                values.put("apn", "tim.br");
                values.put("user", "tim");
                values.put("password", "tim");
                values.put("mcc", mcc);
                values.put("mnc", mnc);
                values.put("numeric", mcc + "" + mnc);
                contentResolver.insert(CONTENT_URI, values);
                cursor = contentResolver.query(CONTENT_URI, new String[] { "_id" },
                        "apn = ? and user = ? and password = ?", new String[] { "tim.br", "tim", "tim" }, null);
            }
        }
        if (cursor == null)
            return;
        if (cursor.moveToFirst())
            id = cursor.getInt(0);
        cursor.close();

        if (id > -1) {
            ContentValues values = new ContentValues();
            //See /etc/apns-conf.xml. The TelephonyProvider uses this file to provide
            //content://telephony/carriers/preferapn URI mapping
            values.put("apn_id", id);
            contentResolver.update(PREFERRED_APN_URI, values, null, null);
            cursor = contentResolver.query(PREFERRED_APN_URI, new String[] { "name", "apn" }, "_id=" + id, null,
                    null);
            if (cursor != null)
                cursor.close();
        }
    }
        break;
    case WIFI:
        connWIFI = connWIFIPrefix + cfg;
        break;
    //default:
    //   throw new IllegalArgumentException("Invalid value for argument 'type'");
    }
}

From source file:com.murrayc.galaxyzoo.app.syncadapter.SyncAdapter.java

private boolean doUploadSync(final String itemId, final String subjectId, final String authName,
        final String authApiKey) throws ZooniverseClient.UploadException {

    //Note: I tried using HttpPost.getParams().setParameter() instead of the NameValuePairs,
    //but that did not allow multiple parameters with the same name, which we need.
    final List<NameValuePair> nameValuePairs = new ArrayList<>();

    nameValuePairs.add(new BasicNameValuePair(PARAM_PART_CLASSIFICATION + "[subject_ids][]", subjectId));

    final ContentResolver resolver = getContentResolver();

    //Mark it as a favorite if necessary:
    {/*from  w w  w. j  a v a2 s  .  c o  m*/
        final String[] projection = { Item.Columns.FAVORITE };
        final Cursor c = resolver.query(Utils.getItemUri(itemId), projection, null, new String[] {}, null);

        if (c.moveToFirst()) {
            final int favorite = c.getInt(0);
            if (favorite == 1) {
                nameValuePairs.add(new BasicNameValuePair(PARAM_PART_CLASSIFICATION + "[favorite][]", "true"));
            }
        }

        c.close();
    }

    final Cursor c;
    {
        final String selection = ClassificationAnswer.Columns.ITEM_ID + " = ?"; //We use ? to avoid SQL Injection.
        final String[] selectionArgs = { itemId };
        final String orderBy = ClassificationAnswer.Columns.SEQUENCE + " ASC";
        c = resolver.query(ClassificationAnswer.CONTENT_URI, PROJECTION_UPLOAD, selection, selectionArgs,
                orderBy);
    }

    int max_sequence = 0;
    while (c.moveToNext()) {
        final int sequence = c.getInt(0);
        final String questionId = c.getString(1);
        final String answerId = c.getString(2);

        //We could instead ORDER BY the sequence but that might be slightly slower and need a index.
        if (sequence > max_sequence) {
            max_sequence = sequence;
        }

        //Add the question's answer:
        //TODO: Is the string representation of sequence locale-dependent?
        final String questionKey = getAnnotationPart(sequence) + "[" + questionId + "]";
        nameValuePairs.add(new BasicNameValuePair(questionKey, answerId));

        final String selection = "(" + ClassificationCheckbox.Columns.ITEM_ID + " = ?) AND " + "("
                + ClassificationCheckbox.Columns.QUESTION_ID + " == ?)"; //We use ? to avoid SQL Injection.
        final String[] selectionArgs = { itemId, questionId };

        //Add the question's answer's selected checkboxes, if any:
        //The sequence will be the same for any selected checkbox for the same answer,
        //so we don't bother getting that, or sorting by that.
        final String[] projection = { ClassificationCheckbox.Columns.CHECKBOX_ID };
        final String orderBy = ClassificationCheckbox.Columns.CHECKBOX_ID + " ASC";
        final Cursor cursorCheckboxes = resolver.query(ClassificationCheckbox.CONTENT_URI, projection,
                selection, selectionArgs, orderBy);

        while (cursorCheckboxes.moveToNext()) {
            final String checkboxId = cursorCheckboxes.getString(0);

            //TODO: The Galaxy-Zoo server expects us to reuse the parameter name,
            //TODO: Is the string representation of sequence locale-dependent?
            nameValuePairs.add(new BasicNameValuePair(questionKey, checkboxId));
        }

        cursorCheckboxes.close();
    }

    c.close();

    //Help the server know that the classification is from this Android app,
    //by reusing the User-Agent string as a parameter value.
    //See https://github.com/murraycu/android-galaxyzoo/issues/11
    final String key = getAnnotationPart(max_sequence + 1) + "[user_agent]";
    nameValuePairs.add(new BasicNameValuePair(key, HttpUtils.USER_AGENT_MURRAYC));

    return mClient.uploadClassificationSync(authName, authApiKey, nameValuePairs);
}

From source file:com.appjma.appdeployer.service.Downloader.java

public void syncApps(String token, Uri uri) throws ClientProtocolException, IOException, JSONException,
        TooManyRecords, WrongHttpResponseCode, UnauthorizedResponseCode {
    String selection = AppContract.Apps.SYNCED + " = 0";
    String[] PROJECTION = new String[] { AppContract.Apps.APP_ID, AppContract.Apps.GUID, AppContract.Apps.NAME,
            AppContract.Apps.DELETED };//from w ww.  ja v  a  2  s.co  m
    Cursor cursor = mCr.query(uri, PROJECTION, selection, null, null);
    try {
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            String id = cursor.getString(0);
            String guid = cursor.getString(1);
            String name = cursor.getString(2);
            boolean deleted = cursor.getInt(3) == 0 ? false : true;
            if (deleted == true) {
                checkState(guid != null, "Row could not be marked as deleted if it is not synced");
                deleteApp(token, id, guid);
            } else if (guid == null) {
                insertApp(token, id, name);
            } else {
                updateApp(token, id, guid, name);
            }
        }
    } finally {
        cursor.close();
    }
}

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.
 *//*  w  w  w.j a  v a 2s . 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:ch.ethz.dcg.jukefox.manager.libraryimport.AndroidAlbumCoverFetcherThread.java

private AlbumFetcherResult extractBitmapsFromMediaProviderCursor(int albumId, Cursor cur) throws Exception {
    int cpAlbumId = cur.getInt(0);
    Uri uri = ContentUris.withAppendedId(sArtworkUri, cpAlbumId);

    if (uri != null) {
        InputStream in = null;/*from   w  w w.  j a  v  a  2 s .c  o m*/
        try {
            in = contentResolver.openInputStream(uri);
            Bitmap bitmapHigh = AndroidUtils.getBitmapFromInputStream(in,
                    2 * AndroidConstants.COVER_SIZE_HIGH_RES);
            bitmapHigh = resizeBitmap(bitmapHigh, AndroidConstants.COVER_SIZE_HIGH_RES);
            if (bitmapHigh == null) {
                return null;
            }
            // Log.v("Got cover from phone DB", album.getArtists().get(0)
            // .getName()
            // + " - "
            // + album.getName()
            // + " "
            // + cpAlbumId
            // + " HResPath: " + highResPath);
            Bitmap bitmapLow = resizeBitmap(bitmapHigh, AndroidConstants.COVER_SIZE_LOW_RES);
            int color = getColorFromBitmap(bitmapLow);
            String lowResPath = getDefaultCoverPath(true, albumId);
            String highResPath = getDefaultCoverPath(false, albumId);
            saveImage(bitmapHigh, highResPath);
            saveImage(bitmapLow, lowResPath);
            return new AlbumFetcherResult(highResPath, lowResPath, color, AlbumStatus.CONTENT_PROVIDER_COVER,
                    albumId);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                Log.w(TAG, ex);
            }
        }
    }
    return null;
}

From source file:com.nextgis.maplibui.formcontrol.Checkbox.java

@Override
public void init(JSONObject element, List<Field> fields, Bundle savedState, Cursor featureCursor,
        SharedPreferences preferences) throws JSONException {

    JSONObject attributes = element.getJSONObject(JSON_ATTRIBUTES_KEY);
    mFieldName = attributes.getString(JSON_FIELD_NAME_KEY);
    mIsShowLast = ControlHelper.isSaveLastValue(attributes);

    Boolean value = null;// www  . j ava 2 s .  co m
    if (ControlHelper.hasKey(savedState, mFieldName))
        value = savedState.getBoolean(ControlHelper.getSavedStateKey(mFieldName));
    else if (null != featureCursor) {
        int column = featureCursor.getColumnIndex(mFieldName);

        if (column >= 0)
            value = featureCursor.getInt(column) != 0;
    } else {
        value = attributes.getBoolean(JSON_INIT_VALUE_KEY);

        if (mIsShowLast)
            value = preferences.getBoolean(mFieldName, value);
    }

    if (value == null)
        value = false;

    setChecked(value);
    setText(attributes.getString(JSON_TEXT_KEY));
    setEnabled(ControlHelper.isEnabled(fields, mFieldName));
}

From source file:org.mythtv.android.db.dvr.ProgramHelperV27.java

public Integer countProgramsByTitle(final Context context, final LocationProfile locationProfile, Uri uri,
        String table, String title) {
    Log.d(TAG, "countProgramsByTitle : enter");

    String[] projection = new String[] { "count(" + table + "." + ProgramConstants.FIELD_TITLE + ")" };
    String selection = table + "." + ProgramConstants.FIELD_TITLE + " = ?";
    String[] selectionArgs = new String[] { title };

    selection = appendLocationHostname(context, locationProfile, selection, table);

    Integer count = null;/*  ww  w .  j  a va 2  s .c  o m*/

    Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
    if (cursor.moveToFirst()) {
        //         Log.v( TAG, "findProgram : program=" + program.toString() );

        count = cursor.getInt(0);
    }
    cursor.close();

    Log.d(TAG, "countProgramsByTitle : exit");
    return count;
}

From source file:com.sourceallies.android.zonebeacon.data.SQLiteQueryTest.java

@Test
public void test_databaseCreated() {
    assertNotNull(source.getDatabase());

    int numTables = 0;
    Cursor cursor = source.getDatabase()
            .rawQuery("SELECT count(*) FROM sqlite_master "
                    + "WHERE type = 'table' AND name != 'android_metadata' AND name != " + "'sqlite_sequence';",
                    null);//w ww .j a v a  2 s.co m
    if (cursor != null && cursor.moveToFirst()) {
        numTables = cursor.getInt(0);
        cursor.close();
    }

    assertTrue(numTables > 0);
}