I need to open an intent to view an image as follows:
Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri = Uri.parse("@drawable/sample_1.jpg"); intent.setData(uri); startActivity(intent);
The problem is that Uri uri = Uri.parse("@drawable/sample_1.jpg");
is incorrect.
You should use ContentResolver to open resource URIs: Uri uri = Uri. parse("android. resource://your.package.here/drawable/image_name"); InputStream stream = getContentResolver().
Occasionally however, you will need to get the actual URI of a resource. All you need to do is replace the package name with your app's package name, as defined in the manifest, and the resource ID of the resource you would like to use. Uri resourceURI = Uri. parse("android.
A URI is a uniform resource identifier while a URL is a uniform resource locator.
AQuery aq = new AQuery(this); aq.id(view). image("http://yourserver/yourimage.png", true, true, 300, new BitmapAjaxCallback() { @Override public void callback(String url, ImageView imageView, Bitmap bitmap, AjaxStatus status) { Drawable drawable = new BitmapDrawable(getResources(), bm); } });
The format is:
"android.resource://[package]/[res id]"
[package] is your package name
[res id] is value of the resource ID, e.g. R.drawable.sample_1
to stitch it together, use
Uri path = Uri.parse("android.resource://your.package.name/" + R.drawable.sample_1);
Here is a clean solution which fully leverages the android.net.Uri
class via its Builder
pattern, avoiding repeated composition and decomposition of the URI string, without relying on hard-coded strings or ad hoc ideas about URI syntax.
Resources resources = context.getResources(); Uri uri = new Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(resources.getResourcePackageName(resourceId)) .appendPath(resources.getResourceTypeName(resourceId)) .appendPath(resources.getResourceEntryName(resourceId)) .build();
Minimally more elegant with Kotlin:
fun Context.resourceUri(resourceId: Int): Uri = with(resources) { Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(getResourcePackageName(resourceId)) .appendPath(getResourceTypeName(resourceId)) .appendPath(getResourceEntryName(resourceId)) .build() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With