Example usage for android.content Context getContentResolver

List of usage examples for android.content Context getContentResolver

Introduction

In this page you can find the example usage for android.content Context getContentResolver.

Prototype

public abstract ContentResolver getContentResolver();

Source Link

Document

Return a ContentResolver instance for your application's package.

Usage

From source file:com.nextgis.mobile.map.Layer.java

protected static String getFileNameByUri(final Context context, Uri uri, String defaultName) {
    String fileName = defaultName;
    Uri filePathUri = uri;/*from   w ww. j  ava 2 s  .co m*/
    try {
        if (uri.getScheme().toString().compareTo("content") == 0) {
            Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
            if (cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
                //Instead of "MediaStore.Images.Media.DATA" can be used "_data"
                filePathUri = Uri.parse(cursor.getString(column_index));
                fileName = filePathUri.getLastPathSegment().toString();
            }
        } else if (uri.getScheme().compareTo("file") == 0) {
            fileName = filePathUri.getLastPathSegment().toString();
        } else {
            fileName = fileName + "_" + filePathUri.getLastPathSegment();
        }
    } catch (Exception e) {
        //do nothing, only return default file name;
        Log.d(TAG, e.getLocalizedMessage());
    }
    return fileName;
}

From source file:edu.mit.mobile.android.livingpostcards.data.Card.java

/**
 * Creates a new card with a random UUID. Cards are marked DRAFT by default.
 *
 * @param cr/*from w w  w .  j a  va  2  s .c  om*/
 * @param cv
 *            initial card contents
 * @return
 */
public static Uri createNewCard(Context context, Account account, ContentValues cv) {

    JsonSyncableItem.addUuid(cv);

    cv.put(Card.COL_DRAFT, true);

    Authorable.putAuthorInformation(context, account, cv);

    final Uri card = context.getContentResolver().insert(Card.CONTENT_URI, cv);

    return card;
}

From source file:jog.my.memory.gcm.ServerUtilities.java

/**
 * Gets the real path of the URI returned from the camera
 * @param contentUri - apparent URI of resource
 * @return - actual URI of resource/*from   w w w.j av a  2s . c o  m*/
 */
public static String getRealPathFromURI(Uri contentUri, Context context) {
    String[] proj = new String[] { MediaStore.Images.ImageColumns.DATA };

    Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();

    String filename = cursor.getString(column_index);
    cursor.close();

    return filename;
}

From source file:com.example.igorklimov.popularmoviesdemo.helpers.Utility.java

public static void addDetails(ContentValues details, ArrayList<ContentValues> allReviews, Context context) {
    ContentResolver resolver = context.getContentResolver();

    ContentValues[] a = new ContentValues[allReviews.size()];
    allReviews.toArray(a);/* ww  w .jav a  2s.c  o m*/

    Log.v(TAG, "addDetails: " + resolver.insert(MovieContract.Details.CONTENT_URI, details));
    Log.v(TAG, "addDetails: " + resolver.bulkInsert(MovieContract.Review.CONTENT_URI, a));
}

From source file:Main.java

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context       The context.// w ww.j  a  va  2 s.  c o m
 * @param uri           The Uri to query.
 * @param selection     (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 * @author paulburke
 */
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = { column };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            if (DEBUG)
                DatabaseUtils.dumpCursor(cursor);

            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } catch (IllegalArgumentException ex) {
        Log.i(TAG, "getDataColumn: _data", ex);
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

From source file:Main.java

/**
 * A safer decodeStream method//  w w  w  .  j av a2s.com
 * rather than the one of {@link BitmapFactory} which will be easy to get OutOfMemory Exception
 * while loading a big image file.
 * 
 * @param uri
 * @param width
 * @param height
 * @return
 * @throws FileNotFoundException
 */
protected static Bitmap safeDecodeStream(Context context, Uri uri, int width, int height)
        throws FileNotFoundException {
    int scale = 1;
    // Decode image size without loading all data into memory  
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    android.content.ContentResolver resolver = context.getContentResolver();
    try {

        BitmapFactory.decodeStream(new BufferedInputStream(resolver.openInputStream(uri), 4 * 1024), null,
                options);
        if (width > 0 || height > 0) {
            options.inJustDecodeBounds = true;
            int w = options.outWidth;
            int h = options.outHeight;
            while (true) {
                if ((width > 0 && w / 2 < width) || (height > 0 && h / 2 < height)) {
                    break;
                }
                w /= 2;
                h /= 2;
                scale *= 2;
            }
        }
        // Decode with inSampleSize option  
        options.inJustDecodeBounds = false;
        options.inSampleSize = scale;
        return BitmapFactory.decodeStream(new BufferedInputStream(resolver.openInputStream(uri), 4 * 1024),
                null, options);
    } catch (Exception e) {
        e.printStackTrace();
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        System.gc();
    }
    return null;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.SharedSecretObj.java

public static byte[] getOrPushSecret(Context context, Contact other) {
    if (other.secret != null) {
        return other.secret;
    }//from  w  ww.ja v a2 s  .  c  o  m
    //TODO: this really needs to be refactored into the contentprovider/helpers etc
    ContentValues values = new ContentValues();
    byte[] ss = new byte[32];
    random.nextBytes(ss);
    values.put(Contact.SHARED_SECRET, ss);
    context.getContentResolver().update(Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/contacts"), values,
            "_id=?", new String[] { String.valueOf(other.id) });
    Helpers.sendMessage(context, other.id, json(ss), TYPE);
    return ss;
}

From source file:com.ushahidi.android.app.util.Util.java

/*** Gets the state of Airplane Mode.        
 * * @param context      //from   w w w.  ja v  a2  s  .  c o m
 * * @return true if enabled.      
 * */
public static boolean isAirplaneModeOn(Context context) {
    return Settings.System.getInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.PictureObj.java

public static DbObject from(Context context, Uri imageUri) throws IOException {
    // Query gallery for camera picture via
    // Android ContentResolver interface
    ContentResolver cr = context.getContentResolver();

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//w w  w . j av  a 2 s. c o  m
    BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options);

    int targetSize = 200;
    int xScale = (options.outWidth + targetSize - 1) / targetSize;
    int yScale = (options.outHeight + targetSize - 1) / targetSize;

    int scale = xScale < yScale ? xScale : yScale;
    //uncomment this to get faster power of two scaling
    //for(int i = 0; i < 32; ++i) {
    //   int mushed = scale & ~(1 << i);
    //   if(mushed != 0)
    //      scale = mushed;
    //}

    options.inJustDecodeBounds = false;
    options.inSampleSize = scale;

    Bitmap sourceBitmap = BitmapFactory.decodeStream(cr.openInputStream(imageUri), null, options);

    int width = sourceBitmap.getWidth();
    int height = sourceBitmap.getHeight();
    int cropSize = Math.min(width, height);

    float scaleSize = ((float) targetSize) / cropSize;

    Matrix matrix = new Matrix();
    matrix.postScale(scaleSize, scaleSize);
    float rotation = PhotoTaker.rotationForImage(context, imageUri);
    if (rotation != 0f) {
        matrix.preRotate(rotation);
    }

    Bitmap resizedBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, width, height, matrix, true);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
    byte[] data = baos.toByteArray();
    sourceBitmap.recycle();
    sourceBitmap = null;
    resizedBitmap.recycle();
    resizedBitmap = null;
    System.gc(); // TODO: gross.

    JSONObject base = new JSONObject();
    if (ContentCorral.CONTENT_CORRAL_ENABLED) {
        try {
            String type = cr.getType(imageUri);
            if (type == null) {
                type = "image/jpeg";
            }
            base.put(CorralClient.OBJ_LOCAL_URI, imageUri.toString());
            base.put(CorralClient.OBJ_MIME_TYPE, type);
            String localIp = ContentCorral.getLocalIpAddress();
            if (localIp != null) {
                base.put(Contact.ATTR_LAN_IP, localIp);
            }
        } catch (JSONException e) {
            Log.e(TAG, "impossible json error possible!");
        }
    }
    return from(base, data);
}

From source file:com.android.emailcommon.utility.AttachmentUtilities.java

/**
 * In support of deleting a mailbox, find all messages and delete their attachments.
 *
 * @param context/*from  w w w. j ava 2s  .  c  om*/
 * @param accountId the account for the mailbox
 * @param mailboxId the mailbox for the messages
 */
public static void deleteAllMailboxAttachmentFiles(Context context, long accountId, long mailboxId) {
    Cursor c = context.getContentResolver().query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION,
            MessageColumns.MAILBOX_KEY + "=?", new String[] { Long.toString(mailboxId) }, null);
    try {
        while (c.moveToNext()) {
            long messageId = c.getLong(Message.ID_PROJECTION_COLUMN);
            deleteAllAttachmentFiles(context, accountId, messageId);
        }
    } finally {
        c.close();
    }
}