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.
The format is:
"android.resource://[package]/[res id]"
to stitch it together, use
Uri path = Uri.parse("android.resource://your.package.name/" + R.drawable.sample_1);
Answer:
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();
Answer:
public static Uri resourceToUri(Context context, int resID) {
return Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
context.getResources().getResourcePackageName(resID) + '/' +
context.getResources().getResourceTypeName(resID) + '/' +
context.getResources().getResourceEntryName(resID) );
}
Answer:
For those having error, you may be entering the wrong package name. Just use this method.
public static Uri resIdToUri(Context context, int resId) {
return Uri.parse(Consts.ANDROID_RESOURCE + context.getPackageName()
+ Consts.FORESLASH + resId);
}
Where
public static final String ANDROID_RESOURCE = "android.resource://";
public static final String FORESLASH = "/";
Answer:
You want the URI of the image resource, and R.drawable.goomb
is an image resource. The Builder function creates the URI that you are asking for:
String resourceScheme = "res";
Uri uri = new Uri.Builder()
.scheme(resourceScheme)
.path(String.valueOf(intResourceId))
.build();
Answer:
Based on the answers above I want to share a kotlin example on how to get a valid Uri for any resource in your project. I think it’s the best solution because you don’t have to type any strings in your code and risk typing it wrongly.
val resourceId = R.raw.scannerbeep // r.mipmap.yourmipmap; R.drawable.yourdrawable
val uriBeepSound = Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(resources.getResourcePackageName(resourceId))
.appendPath(resources.getResourceTypeName(resourceId))
.appendPath(resources.getResourceEntryName(resourceId))
.build()
Tags: androidandroid, image