2011-07-06 19 views
37

Estoy agregando un par de elementos de muestra en mi aplicación para que no se vea tan vacía cuando el usuario lo mire por primera vez. La lista con los elementos de muestra debe tener una imagen y la imagen que voy a usar ya está almacenada en la carpeta/res/dibujable de la aplicación.Obtener el URI de una imagen almacenada en dibujable

Dado que ya tengo un método que carga las imágenes de elementos de un URI, me gustaría obtener el URI en /res/drawable/myImage.jpg, pero parece que no puedo hacerlo bien.

El flujo es el siguiente: Crear elemento con cadena que representa el URI de la imagen. Enviar lista de elementos a una lista La lista carga la imagen en una tarea en segundo plano convirtiendo la cadena en URL y luego ejecuta url.openStream();

He intentado algunas opciones para el URI sin ningún éxito. "android.resource: // ....." protocol desconocido "file: //" dice archivo no encontrado

Así que ahora estoy un poco perdido sobre cómo solucionar este problema ..

+1

La respuesta de @Pixie funciona. –

Respuesta

69

debe utilizar ContentResolver para abrir URI de recursos:

Uri uri = Uri.parse("android.resource://your.package.here/drawable/image_name"); 
InputStream stream = getContentResolver().openInputStream(uri); 

también puede abrir archivos y contenido URI utilizando este método.

+0

Obtengo una excepción MalformedUrlException para lo siguiente: Uri path = Uri.parse ("android.resource: //se.javalia.myDrinks/drawable/image0109 "); La imagen se almacena en la carpeta dibujable y es un archivo jpg. – Roland

+0

Eso es extraño porque' Uri.parse() 'no debe arrojar esta excepción. Cuando se analiza un' Uri' simplemente comprueba si hay una referencia 'null', pero en realidad no lo analiza. – Michael

+0

@Roland Ha cometido un error en alguna parte. Esto funciona muy bien. –

25

Esto es lo que realmente necesita:

Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + 
"://" + getResources().getResourcePackageName(R.drawable.ic_launcher) 
+ '/' + getResources().getResourceTypeName(R.drawable.ic_launcher) + '/' + getResources().getResourceEntryName(R.drawable.ic_launcher)); 
+0

¿Necesita este permiso? No puedo usar este – lirui

+1

No lo creo. ¿Cuál es el error? – xnagyg

33
/** 
* get uri to drawable or any other resource type if u wish 
* @param context - context 
* @param drawableId - drawable res id 
* @return - uri 
*/ 
public static final Uri getUriToDrawable(@NonNull Context context, 
             @AnyRes int drawableId) { 
    Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + 
      "://" + context.getResources().getResourcePackageName(drawableId) 
      + '/' + context.getResources().getResourceTypeName(drawableId) 
      + '/' + context.getResources().getResourceEntryName(drawableId)); 
    return imageUri; 
} 

base en lo anterior - ajustado versión para cualquier recurso:

/** 
* get uri to any resource type 
* @param context - context 
* @param resId - resource id 
* @throws Resources.NotFoundException if the given ID does not exist. 
* @return - Uri to resource by given id 
*/ 
public static final Uri getUriToResource(@NonNull Context context, 
             @AnyRes int resId) 
          throws Resources.NotFoundException { 
    /** Return a Resources instance for your application's package. */ 
    Resources res = context.getResources(); 
    /** 
    * Creates a Uri which parses the given encoded URI string. 
    * @param uriString an RFC 2396-compliant, encoded URI 
    * @throws NullPointerException if uriString is null 
    * @return Uri for this given uri string 
    */ 
    Uri resUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + 
      "://" + res.getResourcePackageName(resId) 
      + '/' + res.getResourceTypeName(resId) 
      + '/' + res.getResourceEntryName(resId)); 
    /** return uri */ 
    return resUri; 
} 

algo de información:

From the Java Language spec.: 

"17.5 Final Field Semantics 

... when the object is seen by another thread, that thread will always 
see the correctly constructed version of that object's final fields. 
It will also see versions of any object or array referenced by 
those final fields that are at least as up-to-date as the final fields 
are." 

In that same vein, all non-transient fields within Uri 
implementations should be final and immutable so as to ensure true 
immutability for clients even when they don't use proper concurrency 
control. 

For reference, from RFC 2396: 

"4.3. Parsing a URI Reference 

    A URI reference is typically parsed according to the four main 
    components and fragment identifier in order to determine what 
    components are present and whether the reference is relative or 
    absolute. The individual components are then parsed for their 
    subparts and, if not opaque, to verify their validity. 

    Although the BNF defines what is allowed in each component, it is 
    ambiguous in terms of differentiating between an authority component 
    and a path component that begins with two slash characters. The 
    greedy algorithm is used for disambiguation: the left-most matching 
    rule soaks up as much of the URI reference string as it is capable of 
    matching. In other words, the authority component wins." 

...

3. URI Syntactic Components 

    The URI syntax is dependent upon the scheme. 
    In general, absolute URI are written as follows: 

    <scheme>:<scheme-specific-part> 

    An absolute URI contains the name of the scheme being used (<scheme>) 
    followed by a colon (":") and then a string (the <scheme-specific-part>) 
    whose interpretation depends on the scheme. 

    The URI syntax does not require that the scheme-specific-part have any 
    general structure or set of semantics which is common among all URI. 
    However, a subset of URI do share a common syntax for representing 
    hierarchical relationships within the namespace. This "generic URI" 
    syntax consists of a sequence of four main components: 

    <scheme>://<authority><path>?<query> 

fuentes:

DISPUTE

esta respuesta es correcta, sin embargo, la parte sobre los campos finales no es - no tiene nada que ver con el answe r - Boris Treukhov

@BorisTreukhov - sírvanse explicar a nosotros lo que entendemos por u "la parte de los campos finales no es correcto" - pregunta - ¿Cómo llegar a uri ...? construir la forma en que se podría analizar (¿cómo se analiza el uri? ver respuesta)

package android.net; 

/** 
* Immutable URI reference. A URI reference includes a URI and a fragment, the 
* component of the URI following a '#'. Builds and parses URI references 
* which conform to 
* <a href="http://www.faqs.org/rfcs/rfc2396.html">RFC 2396</a>. 
* 
* <p>In the interest of performance, this class performs little to no 
* validation. Behavior is undefined for invalid input. This class is very 
* forgiving--in the face of invalid input, it will return garbage 
* rather than throw an exception unless otherwise specified. 
*/ 
public abstract class Uri implements Parcelable, Comparable<Uri> { ... } 
+0

increíble, funciona. gracias –

+0

Esta respuesta es correcta, sin embargo, la parte sobre los campos finales no es - no tiene nada que ver con la respuesta –

+0

@BorisTreukhov - por favor comente en la edición – ceph3us

Cuestiones relacionadas