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.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Called when the camera view exits.// ww w  . j av  a 2 s  . c o m
 *
 * @param requestCode       The request code originally supplied to startActivityForResult(),
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                ExifHelper exif = new ExifHelper();
                try {
                    if (this.encodingType == JPEG) {
                        exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity())
                                + "/.Pic.jpg");
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                    if (rotate != 0 && this.correctOrientation) {
                        bitmap = getRotatedBitmap(rotate, bitmap, exif);
                    }

                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    if (!this.saveToPhotoAlbum) {
                        uri = Uri.fromFile(
                                new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()),
                                        System.currentTimeMillis() + ".jpg"));
                    } else {
                        uri = getUriFromMediaStore();
                    }

                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }

                    // If all this is true we shouldn't compress the image.
                    if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                            && rotate == 0) {
                        writeUncompressedImage(uri);

                        this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                    } else {
                        bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                        if (rotate != 0 && this.correctOrientation) {
                            bitmap = getRotatedBitmap(rotate, bitmap, exif);
                        }

                        // Add compressed version of captured image to returned media store Uri
                        OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                        os.close();

                        // Restore exif data to file
                        if (this.encodingType == JPEG) {
                            String exifPath;
                            if (this.saveToPhotoAlbum) {
                                exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
                            } else {
                                exifPath = uri.getPath();
                            }
                            exif.createOutFile(exifPath);
                            exif.writeExifData();
                        }

                    }
                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                }

                this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
                bitmap = null;

            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();

            // If you ask for video or all media type you will automatically get back a file URI
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
            } else {
                // This is a special case to just return the path as no scaling,
                // rotating or compression needs to be done
                if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                        && destType == FILE_URI && !this.correctOrientation) {
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                } else {
                    // Get the path to the image. Makes loading so much easier.
                    String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
                    Log.d(LOG_TAG, "Real path = " + imagePath);
                    // If we don't have a valid image so quit.
                    if (imagePath == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to retreive path to picture!");
                        return;
                    }
                    Bitmap bitmap = getScaledBitmap(imagePath);
                    if (bitmap == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to create bitmap!");
                        return;
                    }

                    if (this.correctOrientation) {
                        String[] cols = { MediaStore.Images.Media.ORIENTATION };
                        Cursor cursor = this.cordova.getActivity().getContentResolver().query(intent.getData(),
                                cols, null, null, null);
                        if (cursor != null) {
                            cursor.moveToPosition(0);
                            rotate = cursor.getInt(0);
                            cursor.close();
                        }
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            matrix.setRotate(rotate);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                        }
                    }

                    // If sending base64 image back
                    if (destType == DATA_URL) {
                        this.processPicture(bitmap);
                    }

                    // If sending filename back
                    else if (destType == FILE_URI) {
                        // Do we need to scale the returned file
                        if (this.targetHeight > 0 && this.targetWidth > 0) {
                            try {
                                // Create an ExifHelper to save the exif data that is lost during compression
                                String resizePath = DirectoryManager
                                        .getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
                                ExifHelper exif = new ExifHelper();
                                try {
                                    if (this.encodingType == JPEG) {
                                        exif.createInFile(resizePath);
                                        exif.readExifData();
                                        rotate = exif.getOrientation();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                OutputStream os = new FileOutputStream(resizePath);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                                os.close();

                                // Restore exif data to file
                                if (this.encodingType == JPEG) {
                                    exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
                                    exif.writeExifData();
                                }

                                // The resized image is cached by the app in order to get around this and not have to delete you
                                // application cache I'm adding the current system time to the end of the file url.
                                this.success(
                                        new PluginResult(PluginResult.Status.OK,
                                                ("file://" + resizePath + "?" + System.currentTimeMillis())),
                                        this.callbackId);
                            } catch (Exception e) {
                                e.printStackTrace();
                                this.failPicture("Error retrieving image.");
                            }
                        } else {
                            this.success(new PluginResult(PluginResult.Status.OK, uri.toString()),
                                    this.callbackId);
                        }
                    }
                    if (bitmap != null) {
                        bitmap.recycle();
                        bitmap = null;
                    }
                    System.gc();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:com.phonegap.ContactAccessorSdk3_4.java

/**
 * Create a ContactField JSONArray/*from ww  w  . j  ava  2 s  . c o m*/
 * @param cr database access object
 * @param contactId the ID to search the database for
 * @return a JSONArray representing a set of ContactFields
 */
private JSONArray imQuery(ContentResolver cr, String contactId) {
    String imWhere = ContactMethods.PERSON_ID + " = ? AND " + ContactMethods.KIND + " = ?";
    String[] imWhereParams = new String[] { contactId, ContactMethods.CONTENT_IM_ITEM_TYPE };
    Cursor cursor = cr.query(ContactMethods.CONTENT_URI, null, imWhere, imWhereParams, null);
    JSONArray ims = new JSONArray();
    JSONObject im;
    while (cursor.moveToNext()) {
        im = new JSONObject();
        try {
            im.put("id", cursor.getString(cursor.getColumnIndex(ContactMethods._ID)));
            im.put("perf", false);
            im.put("value", cursor.getString(cursor.getColumnIndex(ContactMethodsColumns.DATA)));
            im.put("type", getContactType(cursor.getInt(cursor.getColumnIndex(ContactMethodsColumns.TYPE))));
            ims.put(im);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    cursor.close();
    return null;
}

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

public List<Integer> get_records(String table, String condition, String field) {
    List<Integer> list = new ArrayList<Integer>();
    try {// ww  w .  j a  v  a2  s  . c o  m
        Cursor cursor = db.query(table, null, condition, null, null, null, null, null);

        int idColumn = cursor.getColumnIndex(field);
        int bundle_id_col = cursor.getColumnIndex("bundle_id");
        int bundle_source_col = cursor.getColumnIndex("source");
        int bundle_destination_col = cursor.getColumnIndex("destination");
        int bundle_message_col = cursor.getColumnIndex("msg");
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {

                    list.add(cursor.getInt(idColumn));

                    Log.d(TAG, "Found it@:" + cursor.getInt(idColumn));
                    Log.d(TAG, "Found it@:" + cursor.getString(bundle_id_col));
                    Log.d(TAG, "Found it@:" + cursor.getString(bundle_source_col));
                    Log.d(TAG, "Found it@:" + cursor.getString(bundle_destination_col));
                    Log.d(TAG, "Found it@:" + cursor.getString(bundle_message_col));

                } while (cursor.moveToNext());
            }
        } 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 list;
}

From source file:com.flowzr.export.flowzr.FlowzrSyncEngine.java

private static JSONObject cursorToDict(String tableName, Cursor c) {
    int totalColumn = c.getColumnCount();
    JSONObject rowObject = new JSONObject();
    if (c.getColumnIndex("_id") != -1) {
        try {//  w  w w .j a v  a  2 s .co  m
            rowObject.put("_id", c.getInt(c.getColumnIndex("_id")));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    for (int i = 0; i < totalColumn; i++) {
        if (c.getColumnName(i) != null) {
            String colName = c.getColumnName(i);
            try {
                if (c.getString(i) != null) {
                    if (colName.endsWith("_id") || colName.equals("parent")) {
                        if (tableName.equals(DatabaseHelper.BUDGET_TABLE)) {
                            if (colName.equals("parent_budget_id")) {
                                rowObject.put(colName, c.getInt(i));
                            } else if (!colName.equals("_id")) {
                                String[] entities = c.getString(c.getColumnIndex(colName)).split(",");
                                String keys = "";
                                for (String entity_id2 : entities) {
                                    keys += getRemoteKey(getTableForColName(colName), entity_id2) + ",";
                                }
                                if (keys.endsWith(",")) {
                                    keys = keys.substring(0, keys.length() - 1);
                                }
                                rowObject.put(colName, keys);
                            }
                        } else {
                            if (!colName.equals("_id")) {
                                String k = getRemoteKey(getTableForColName(colName), c.getString(i));
                                if (k != null) {
                                    rowObject.put(colName, k);
                                } else {
                                    rowObject.put(colName, c.getInt(i));
                                }
                            }
                        }
                    } else {
                        rowObject.put(colName, c.getString(c.getColumnIndex(colName)));
                    }
                    /****/
                    if (tableName.equals(DatabaseHelper.ACCOUNT_TABLE)) {
                        String sql = "select max(dateTime) as maxDate, min(dateTime) as minDate from "
                                + DatabaseHelper.TRANSACTION_TABLE + " where from_account_id="
                                + c.getInt(c.getColumnIndex("_id"));
                        Cursor c2 = db.rawQuery(sql, null);
                        c2.moveToFirst();
                        rowObject.put("dateOfFirstTransaction", c2.getString(1));
                        rowObject.put("dateOfLastTransaction", c2.getString(0));
                        //each account can have a timezone so you can have a balance at closing day               
                        rowObject.put("tz", String.valueOf(TimeZone.getDefault().getRawOffset()));
                    } else if (tableName.equals(DatabaseHelper.CATEGORY_TABLE)) {
                        //load parent id
                        Category cat = dba.getCategory(c.getInt(0)); // sql build/load parentId   
                        if (cat.getParentId() > 0) {
                            Category pcat = em.load(Category.class, cat.getParentId());
                            rowObject.put("parent", pcat.remoteKey);
                            rowObject.put("parent_id", pcat.id);

                        }
                        String attrPushString = "";

                        for (Attribute attr : dba.getAttributesForCategory(c.getInt(0))) {
                            attrPushString = attrPushString + attr.remoteKey + ";";
                        }
                        if (attrPushString != "") {
                            rowObject.put("attributes", attrPushString);
                        }
                    } else if (tableName.equals(DatabaseHelper.TRANSACTION_TABLE)) {
                        Map<Long, String> attributesMap = dba.getAllAttributesForTransaction(c.getInt(0));
                        String transaction_attribute = "";
                        for (long attributeId : attributesMap.keySet()) {
                            transaction_attribute += dba.getAttribute(attributeId).remoteKey + "="
                                    + attributesMap.get(attributeId) + ";";
                        }
                        rowObject.put("transaction_attribute", transaction_attribute);
                    }
                    /****/
                } else {
                    rowObject.put(colName, "");
                }
            } catch (JSONException e) {
                Log.d(TAG, e.getMessage());
            }
        }
    }
    return rowObject;
}

From source file:com.buddi.client.dfu.DfuActivity.java

@Override
public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) {
    if (data != null && data.moveToNext()) {
        /*/*  w w w.  j  a v a  2  s  .  com*/
         * 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;

        updateFileInfo(fileName, fileSize, mFileType);
    } else {
        mFileNameView.setText(null);
        mFileTypeView.setText(null);
        mFileSizeView.setText(null);
        mFilePath = null;
        mFileStreamUri = null;
        mFileStatusView.setText(R.string.dfu_file_status_error);
        mStatusOk = false;
    }
}

From source file:me.myatminsoe.myansms.Message.java

/**
 * Fetch MMS parts.//  ww  w  .  jav  a  2s.c  om
 *
 * @param context {@link Context}
 */
private void fetchMmsParts(final Context context) {
    final ContentResolver cr = context.getContentResolver();
    Cursor cursor = cr.query(URI_PARTS, null, PROJECTION_PARTS[INDEX_MID] + " = ?",
            new String[] { String.valueOf(id) }, null);
    if (cursor == null || !cursor.moveToFirst()) {
        return;
    }
    final int iID = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_ID]);
    final int iCT = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_CT]);
    final int iText = cursor.getColumnIndex("text");
    do {
        final int pid = cursor.getInt(iID);
        final String ct = cursor.getString(iCT);

        // get part
        InputStream is = null;

        final Uri uri = ContentUris.withAppendedId(URI_PARTS, pid);
        if (uri == null) {

            continue;
        }
        try {
            is = cr.openInputStream(uri);
        } catch (IOException | NullPointerException e) {

        }
        if (is == null) {

            if (iText >= 0 && ct != null && ct.startsWith("text/")) {
                body = cursor.getString(iText);
            }
            continue;
        }
        if (ct == null) {
            continue;
        }
        if (ct.startsWith("image/")) {
            picture = BitmapFactory.decodeStream(is);
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("video/") || ct.startsWith("audio/")) {
            picture = BITMAP_PLAY;
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("text/")) {
            body = fetchPart(is);
        }

        try {
            is.close();
        } catch (IOException e) {
        } // Ignore
    } while (cursor.moveToNext());
}

From source file:com.odoo.core.orm.OModel.java

public int selectRowId(String selection, String[] args) {
    int row_id = INVALID_ROW_ID;
    SQLiteDatabase db = getReadableDatabase();
    Cursor cr = db.query(getTableName(), new String[] { OColumn.ROW_ID }, selection, args, null, null, null);
    try {//from   www. j  a v a 2s  .c  o  m
        if (cr.moveToFirst()) {
            row_id = cr.getInt(0);
        }
    } finally {
        cr.close();
    }
    return row_id;
}

From source file:com.beesham.popularmovies.DetailsFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (!data.moveToFirst()) {
        return;/*from  w  w w. ja  va 2s .  c o m*/
    }

    getActivity().findViewById(R.id.details_linear_layout).setVisibility(View.VISIBLE);

    switch (loader.getId()) {
    case 1:
        titleTextView
                .setText(data.getString(data.getColumnIndex(MoviesContract.MoviesEntry.COLUMN_MOVIE_TITLE)));
        Picasso.with(getContext())
                .load(data.getString(data.getColumnIndex(MoviesContract.MoviesEntry.COLUMN_MOVIE_POSTER)))
                .into(posterImageView);
        overviewTextView
                .setText(data.getString(data.getColumnIndex(MoviesContract.MoviesEntry.COLUMN_MOVIE_SYNOPSIS)));
        ratingsTextView.setText(getString(R.string.rating,
                data.getInt(data.getColumnIndex(MoviesContract.MoviesEntry.COLUMN_MOVIE_USER_RATING))));
        releaseDateTextView.setText(parseReleaseYear(data
                .getString(data.getColumnIndex(MoviesContract.MoviesFavoriteEntry.COLUMN_MOVIE_RELEASE_DATE))));
        mTrailersJSONStr = data
                .getString(data.getColumnIndex(MoviesContract.MoviesEntry.COLUMN_MOVIE_TRAILERS));
        mReviewJSONStr = data.getString(data.getColumnIndex(MoviesContract.MoviesEntry.COLUMN_MOVIE_REVIEWS));
        break;

    case 2:
        titleTextView.setText(
                data.getString(data.getColumnIndex(MoviesContract.MoviesFavoriteEntry.COLUMN_MOVIE_TITLE)));
        Picasso.with(getContext())
                .load(data
                        .getString(data.getColumnIndex(MoviesContract.MoviesFavoriteEntry.COLUMN_MOVIE_POSTER)))
                .into(posterImageView);
        overviewTextView.setText(
                data.getString(data.getColumnIndex(MoviesContract.MoviesFavoriteEntry.COLUMN_MOVIE_SYNOPSIS)));
        ratingsTextView.setText(getString(R.string.rating,
                data.getInt(data.getColumnIndex(MoviesContract.MoviesFavoriteEntry.COLUMN_MOVIE_USER_RATING))));
        releaseDateTextView.setText(parseReleaseYear(data
                .getString(data.getColumnIndex(MoviesContract.MoviesFavoriteEntry.COLUMN_MOVIE_RELEASE_DATE))));
        mTrailersJSONStr = data
                .getString(data.getColumnIndex(MoviesContract.MoviesFavoriteEntry.COLUMN_MOVIE_TRAILERS));
        mReviewJSONStr = data
                .getString(data.getColumnIndex(MoviesContract.MoviesFavoriteEntry.COLUMN_MOVIE_REVIEWS));
        break;
    }

    //Clear the lists of old data if any
    mTrailerList.clear();
    mReviewsList.clear();

    parseTrailers();
    parseReview();
    mCursor = data;

    //Check if the movie is favorite so appropriate
    // button state can be placed
    if (checkForFavorite()) {
        favoriteButton.setText(R.string.mark_unfavorite);
    }
}

From source file:com.heneryh.aquanotes.service.SyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    Log.d(TAG, "onHandleIntent(intent=" + intent.toString() + ")");

    /**/*from w  w  w  .j  a v a  2 s . c  om*/
     * Using the intent, we can tell why we are running this service
     */
    Cursor cursor = null;

    // This came from the timer expiring or from the gui, either way, push all controllers onto the queue.
    if (ACTION_UPDATE_ALL.equals(intent.getAction()) || Intent.ACTION_SYNC.equals(intent.getAction())) {
        try {
            Uri controllersQueryUri = Controllers.buildQueryControllersUri();
            cursor = dbResolverSyncSrvc.query(controllersQueryUri, ControllersQuery.PROJECTION, null, null,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                while (!cursor.isAfterLast()) {
                    Integer controllerId = cursor.getInt(ControllersQuery._ID);
                    requestUpdate(controllerId);
                    cursor.moveToNext();
                }
            }
        } catch (SQLException e) {
            Log.e(TAG, "getting controller list", e);
            // need a little more here!
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } else if (ACTION_UPDATE_SINGLE.equals(intent.getAction())) { // This came from the a widget update, id is in the queue

    }

    /**
     *  Only start processing thread if not already running, if the thread was running it would
     *  grab the queue items
     */
    synchronized (sLock) {
        if (!sThreadRunning) {
            sThreadRunning = true;
            new SyncThread().execute();
        }
    }
}

From source file:org.dvbviewer.controller.ui.fragments.ChannelList.java

/**
 * Reads the current cursorposition to a Channel.
 *
 * @param c the c//from   w w  w.  j a v  a 2s. c o  m
 * @return the Channel
 * @author RayBa
 * @date 13.05.2012
 */
private Channel cursorToChannel(Cursor c) {
    Channel channel = new Channel();
    channel.setId(c.getLong(c.getColumnIndex(ChannelTbl._ID)));
    channel.setEpgID(c.getLong(c.getColumnIndex(ChannelTbl.EPG_ID)));
    String name = c.getString(c.getColumnIndex(ChannelTbl.NAME));
    channel.setName(name);
    channel.setPosition(c.getInt(c.getColumnIndex(ChannelTbl.POSITION)));
    return channel;
}