Example usage for android.app Activity getContentResolver

List of usage examples for android.app Activity getContentResolver

Introduction

In this page you can find the example usage for android.app Activity getContentResolver.

Prototype

@Override
    public ContentResolver getContentResolver() 

Source Link

Usage

From source file:com.native5.plugins.ActionBarPlugin.java

private Drawable getDrawableForURI(String uri_string) {
    Uri uri = Uri.parse(uri_string);//  w  w w  .ja  v a  2s.c om
    Activity ctx = (Activity) cordova;

    // Special case - TrueType fonts
    if (uri_string.endsWith(".ttf")) {
        /*for(String base: bases)
        {
           String path = base + uri;
                   
           // TODO: Font load / glyph rendering ("/blah/fontawesome.ttf:\f1234")
        }*/
    }
    // General bitmap
    else {
        if (uri.isAbsolute()) {
            if (uri.getScheme().startsWith("http")) {
                try {
                    URL url = new URL(uri_string);
                    InputStream stream = url.openConnection().getInputStream();
                    return new BitmapDrawable(ctx.getResources(), stream);
                } catch (MalformedURLException e) {
                    return null;
                } catch (IOException e) {
                    return null;
                } catch (Exception e) {
                    return null;
                }
            } else {
                try {
                    InputStream stream = ctx.getContentResolver().openInputStream(uri);
                    return new BitmapDrawable(ctx.getResources(), stream);
                } catch (FileNotFoundException e) {
                    return null;
                }
            }
        } else {
            for (String base : bases) {
                String path = base + uri;

                // Asset
                if (base.startsWith("file:///android_asset/")) {
                    path = path.substring(22);

                    try {
                        InputStream stream = ctx.getAssets().open(path);
                        return new BitmapDrawable(ctx.getResources(), stream);
                    } catch (IOException e) {
                        continue;
                    }
                }
                // General URI
                else {
                    try {
                        InputStream stream = ctx.getContentResolver().openInputStream(Uri.parse(path));
                        return new BitmapDrawable(ctx.getResources(), stream);
                    } catch (FileNotFoundException e) {
                        continue;
                    }
                }
            }
        }
    }

    return null;
}

From source file:com.kncwallet.wallet.ui.SendCoinsFragment.java

@Override
public void onAttach(final Activity activity) {
    super.onAttach(activity);

    this.activity = (AbstractBindServiceActivity) activity;
    this.application = (WalletApplication) activity.getApplication();
    this.prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    this.wallet = application.getWallet();
    this.contentResolver = activity.getContentResolver();
    this.loaderManager = getLoaderManager();

}

From source file:com.apptentive.android.sdk.module.engagement.interaction.fragment.MessageCenterFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
        case Constants.REQUEST_CODE_CLOSE_COMPOSING_CONFIRMATION: {
            onCancelComposing();/*www  .jav  a 2  s  .c om*/
            break;
        }
        case Constants.REQUEST_CODE_PHOTO_FROM_SYSTEM_PICKER: {
            if (data == null) {
                ApptentiveLog.d("no image is picked");
                return;
            }
            imagePickerStillOpen = false;
            Uri uri;
            Activity hostingActivity = hostingActivityRef.get();
            //Android SDK less than 19
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                uri = data.getData();
            } else {
                //for Android 4.4
                uri = data.getData();
                int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
                if (hostingActivity != null) {
                    hostingActivity.getContentResolver().takePersistableUriPermission(uri, takeFlags);
                }
            }

            EngagementModule.engageInternal(getActivity(), interaction,
                    MessageCenterInteraction.EVENT_NAME_ATTACH);

            String originalPath = Util.getRealFilePathFromUri(hostingActivity, uri);
            if (originalPath != null) {
                /* If able to retrieve file path and creation time from uri, cache file name will be generated
                 * from the md5 of file path + creation time
                 */
                long creation_time = Util.getContentCreationTime(hostingActivity, uri);
                Uri fileUri = Uri.fromFile(new File(originalPath));
                File cacheDir = Util.getDiskCacheDir(hostingActivity);
                addAttachmentsToComposer(new ImageItem(originalPath,
                        Util.generateCacheFileFullPath(fileUri, cacheDir, creation_time),
                        Util.getMimeTypeFromUri(hostingActivity, uri), creation_time));
            } else {
                /* If not able to get image file path due to not having READ_EXTERNAL_STORAGE permission,
                 * cache name will be generated from md5 of uri string
                 */
                File cacheDir = Util.getDiskCacheDir(hostingActivity);
                String cachedFileName = Util.generateCacheFileFullPath(uri, cacheDir, 0);
                addAttachmentsToComposer(new ImageItem(uri.toString(), cachedFileName,
                        Util.getMimeTypeFromUri(hostingActivity, uri), 0));
            }

            break;
        }
        default:
            break;
        }
    }
}

From source file:com.rjfun.cordova.sms.SMSPlugin.java

protected void createContentObserver() {
    Activity ctx = this.cordova.getActivity();
    this.mObserver = new ContentObserver(new Handler()) {

        public void onChange(boolean selfChange) {
            this.onChange(selfChange, null);
        }//from w ww.  j  a va2  s.  c om

        public void onChange(boolean selfChange, Uri uri) {
            ContentResolver resolver = cordova.getActivity().getContentResolver();
            Log.d(LOGTAG, ("onChange, selfChange: " + selfChange + ", uri: " + (Object) uri));
            int id = -1;
            String str;
            if (uri != null && (str = uri.toString()).startsWith(SMS_URI_ALL)) {
                try {
                    id = Integer.parseInt(str.substring(SMS_URI_ALL.length()));
                    Log.d(LOGTAG, ("sms id: " + id));
                } catch (NumberFormatException var6_6) {
                    // empty catch block
                }
            }
            if (id == -1) {
                uri = Uri.parse(SMS_URI_INBOX);
            }
            Cursor cur = resolver.query(uri, null, null, null, "_id desc");
            if (cur != null) {
                int n = cur.getCount();
                Log.d(LOGTAG, ("n = " + n));
                if (n > 0 && cur.moveToFirst()) {
                    JSONObject json;
                    if ((json = SMSPlugin.this.getJsonFromCursor(cur)) != null) {
                        onSMSArrive(json);
                    } else {
                        Log.d(LOGTAG, "fetch record return null");
                    }
                }
                cur.close();
            }
        }
    };
    ctx.getContentResolver().registerContentObserver(Uri.parse(SMS_URI_INBOX), true, this.mObserver);
    Log.d(LOGTAG, "sms inbox observer registered");
}

From source file:org.cryptsecure.Utility.java

/**
 * Convert the image URI to the direct file system path of the image so that
 * it can be loaded./*from  w  ww  .  j  a  va  2 s  .  c o  m*/
 * 
 * @param contentUri
 *            the content uri
 * @return the real path from uri
 */
@SuppressLint("NewApi")
// file
@SuppressWarnings("deprecation")
public static String getRealPathFromURI(Activity activity, Uri contentUri) {
    String returnPath = null;

    Log.d("communicator", "IMPORT getRealPathFromURI() contentUri=" + contentUri.toString());

    try {
        if (Build.VERSION.SDK_INT < 19) {
            // can post image
            String[] proj = { MediaStore.Images.Media.DATA };
            Cursor cursor = activity.managedQuery(contentUri, proj, // Which
                    // columns
                    // to
                    // return
                    null, // WHERE clause; which rows to return (all rows)
                    null, // WHERE clause selection arguments (none)
                    null); // Order-by clause (ascending by name)
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            returnPath = cursor.getString(column_index);
        } else if (Build.VERSION.SDK_INT > 19) {
            String[] projection = { MediaStore.Images.Media.DATA };
            String wholeID = DocumentsContract.getDocumentId(contentUri);
            String id = wholeID.split(":")[1];
            String sel = MediaStore.Images.Media._ID + "=?";
            Cursor cursor = activity.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    projection, sel, new String[] { id }, null);
            int column_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            returnPath = cursor.getString(column_index).toString();
            cursor.close();
        } else {
            returnPath = contentUri.toString();
        }
    } catch (Exception e) {
    }

    Log.d("communicator", "IMPORT getRealPathFromURI() returnPath=" + returnPath);

    return returnPath;
}

From source file:com.android.browser.BookmarksPageCallbacks.java

public boolean handleContextItem(int itemId, int groupPosition, int childPosition) {
    final Activity activity = getActivity();
    BrowserBookmarksAdapter adapter = getChildAdapter(groupPosition);

    switch (itemId) {
    case R.id.open_context_menu_id:
        loadUrl(adapter, childPosition);
        break;/*from  ww w.  j a  v  a2  s  . c om*/
    case R.id.edit_context_menu_id:
        editBookmark(adapter, childPosition);
        break;
    case R.id.shortcut_context_menu_id:
        Cursor c = adapter.getItem(childPosition);
        activity.sendBroadcast(createShortcutIntent(getActivity(), c));
        break;
    case R.id.delete_context_menu_id:
        displayRemoveBookmarkDialog(adapter, childPosition);
        break;
    case R.id.new_window_context_menu_id:
        openInNewWindow(adapter, childPosition);
        break;
    case R.id.share_link_context_menu_id: {
        Cursor cursor = adapter.getItem(childPosition);
        Controller.sharePage(activity, cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE),
                cursor.getString(BookmarksLoader.COLUMN_INDEX_URL),
                getBitmap(cursor, BookmarksLoader.COLUMN_INDEX_FAVICON),
                getBitmap(cursor, BookmarksLoader.COLUMN_INDEX_THUMBNAIL));
        break;
    }
    case R.id.copy_url_context_menu_id:
        copy(getUrl(adapter, childPosition));
        break;
    case R.id.homepage_context_menu_id: {
        BrowserSettings.getInstance().setHomePage(getUrl(adapter, childPosition));
        Toast.makeText(activity, R.string.homepage_set, Toast.LENGTH_LONG).show();
        break;
    }
    // Only for the Most visited page
    case R.id.save_to_bookmarks_menu_id: {
        Cursor cursor = adapter.getItem(childPosition);
        String name = cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE);
        String url = cursor.getString(BookmarksLoader.COLUMN_INDEX_URL);
        // If the site is bookmarked, the item becomes remove from
        // bookmarks.
        Bookmarks.removeFromBookmarks(activity, activity.getContentResolver(), url, name);
        break;
    }
    default:
        return false;
    }
    return true;
}

From source file:com.borqs.browser.BookmarksPageCallbacks.java

public boolean handleContextItem(int itemId, int groupPosition, int childPosition) {
    final Activity activity = getActivity();
    BrowserBookmarksAdapter adapter = getChildAdapter(groupPosition);

    switch (itemId) {
    case R.id.open_context_menu_id:
        loadUrl(adapter, childPosition);
        break;/*from  ww  w  .ja  v a  2  s. c  om*/
    case R.id.edit_context_menu_id:
        editBookmark(adapter, childPosition);
        break;
    case R.id.shortcut_context_menu_id:
        Cursor c = adapter.getItem(childPosition);
        activity.sendBroadcast(createShortcutIntent(getActivity(), c));
        break;
    case R.id.delete_context_menu_id:
        displayRemoveBookmarkDialog(adapter, childPosition);
        break;
    case R.id.new_window_context_menu_id:
        openInNewWindow(adapter, childPosition);
        break;
    case R.id.share_link_context_menu_id: {
        /*
         Cursor cursor = adapter.getItem(childPosition);
         Controller.sharePage(activity,
            cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE),
            cursor.getString(BookmarksLoader.COLUMN_INDEX_URL),
            getBitmap(cursor, BookmarksLoader.COLUMN_INDEX_FAVICON),
            getBitmap(cursor, BookmarksLoader.COLUMN_INDEX_THUMBNAIL));
            */
        break;
    }
    case R.id.copy_url_context_menu_id:
        copy(getUrl(adapter, childPosition));
        break;
    case R.id.homepage_context_menu_id: {
        // BrowserSettings.getInstance().setHomePage(getUrl(adapter, childPosition));
        Toast.makeText(activity, R.string.homepage_set, Toast.LENGTH_LONG).show();
        break;
    }
    // Only for the Most visited page
    case R.id.save_to_bookmarks_menu_id: {
        Cursor cursor = adapter.getItem(childPosition);
        String name = cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE);
        String url = cursor.getString(BookmarksLoader.COLUMN_INDEX_URL);
        // If the site is bookmarked, the item becomes remove from
        // bookmarks.
        Bookmarks.removeFromBookmarks(activity, activity.getContentResolver(), url, name);
        break;
    }
    default:
        return false;
    }
    return true;
}

From source file:com.borqs.browser.combo.BookmarksPageCallbacks.java

public boolean handleContextItem(int itemId, int groupPosition, int childPosition) {
    final Activity activity = this;
    BrowserBookmarksAdapter adapter = getChildAdapter(groupPosition);

    switch (itemId) {
    case R.id.open_context_menu_id:
        loadUrl(adapter, childPosition);
        break;/* w  w  w . jav a  2s . c o m*/
    case R.id.edit_context_menu_id:
        editBookmark(adapter, childPosition);
        break;
    case R.id.shortcut_context_menu_id:
        Cursor c = adapter.getItem(childPosition);
        activity.sendBroadcast(createShortcutIntent(this, c));
        break;
    case R.id.delete_context_menu_id:
        displayRemoveBookmarkDialog(adapter, childPosition);
        break;
    case R.id.new_window_context_menu_id:
        openInNewWindow(adapter, childPosition);
        break;
    case R.id.share_link_context_menu_id: {
        /*
         Cursor cursor = adapter.getItem(childPosition);
         Controller.sharePage(activity,
            cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE),
            cursor.getString(BookmarksLoader.COLUMN_INDEX_URL),
            getBitmap(cursor, BookmarksLoader.COLUMN_INDEX_FAVICON),
            getBitmap(cursor, BookmarksLoader.COLUMN_INDEX_THUMBNAIL));
            */
        break;
    }
    case R.id.copy_url_context_menu_id:
        copy(getUrl(adapter, childPosition));
        break;
    case R.id.homepage_context_menu_id: {
        // BrowserSettings.getInstance().setHomePage(getUrl(adapter, childPosition));
        Toast.makeText(activity, R.string.homepage_set, Toast.LENGTH_LONG).show();
        break;
    }
    // Only for the Most visited page
    case R.id.save_to_bookmarks_menu_id: {
        Cursor cursor = adapter.getItem(childPosition);
        String name = cursor.getString(BookmarksLoader.COLUMN_INDEX_TITLE);
        String url = cursor.getString(BookmarksLoader.COLUMN_INDEX_URL);
        // If the site is bookmarked, the item becomes remove from
        // bookmarks.
        Bookmarks.removeFromBookmarks(activity, activity.getContentResolver(), url, name);
        break;
    }
    default:
        return false;
    }
    return true;
}

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

/**
 * Get a {@link OnLongClickListener} to save the attachment.
 *
 * @param context {@link Context}//from   w  ww.  j av  a 2  s  .co  m
 * @return {@link OnLongClickListener}
 */
public OnLongClickListener getSaveAttachmentListener(final Activity context) {
    if (contentIntent == null) {
        return null;
    }

    return new OnLongClickListener() {
        @Override
        public boolean onLongClick(final View v) {
            // check/request permission Manifest.permission.WRITE_EXTERNAL_STORAGE
            if (!SMSdroid.requestPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE, 0,
                    R.string.permissions_write_external_storage, null)) {
                return true;
            }

            try {
                String fn = ATTACHMENT_FILE;
                final Intent ci = Message.this.contentIntent;
                final String ct = ci.getType();
                if (ct == null) {
                    fn += "null";
                } else if (ct.startsWith("image/")) {
                    switch (ct) {
                    case "image/jpeg":
                        fn += "jpg";
                        break;
                    case "image/gif":
                        fn += "gif";
                        break;
                    default:
                        fn += "png";
                        break;
                    }
                } else if (ct.startsWith("audio/")) {
                    switch (ct) {
                    case "audio/3gpp":
                        fn += "3gpp";
                        break;
                    case "audio/mpeg":
                        fn += "mp3";
                        break;
                    case "audio/mid":
                        fn += "mid";
                        break;
                    default:
                        fn += "wav";
                        break;
                    }
                } else if (ct.startsWith("video/")) {
                    if (ct.equals("video/3gpp")) {
                        fn += "3gpp";
                    } else {
                        fn += "avi";
                    }
                } else {
                    fn += "ukn";
                }
                final File file = Message.this.createUniqueFile(Environment.getExternalStorageDirectory(), fn);
                //noinspection ConstantConditions
                InputStream in = context.getContentResolver().openInputStream(ci.getData());
                OutputStream out = new FileOutputStream(file);
                IOUtils.copy(in, out);
                out.flush();
                out.close();
                //noinspection ConstantConditions
                in.close();

                Toast.makeText(context, context.getString(R.string.attachment_saved) + " " + fn,
                        Toast.LENGTH_LONG).show();
                return true;
            } catch (IOException e) {

                Toast.makeText(context, R.string.attachment_not_saved, Toast.LENGTH_LONG).show();
            } catch (NullPointerException e) {

                Toast.makeText(context, R.string.attachment_not_saved, Toast.LENGTH_LONG).show();
            }
            return true;
        }
    };
}