2011-07-06 8 views
37

私はアプリケーションでいくつかのサンプル項目を追加していますので、ユーザーが最初に見たときに空に見えません。サンプル項目のリストにはイメージがあり、使用するイメージはすでにアプリケーションの/ res/drawable-folderに保存されています。drawableに格納されている画像のURIを取得

URIから項目イメージを読み込むメソッドが既にあるので、URIを/res/drawable/myImage.jpgに取得したいのですが、正しく取得できないようです。

フローは次のとおりです。 イメージのURIを表す文字列でアイテムを作成します。 リストの項目リストをリストに送信 リストは、文字列をURLに変換してからurl.openStream()を実行することによって、バックグラウンドタスクのイメージをロードします。

URIのいくつかのオプションを試してみましたが、何の成功もありませんでした。 「android.resource:// .....」unknowのprotocoll 「ファイル://」というファイル

を見つけていないが、だから、今、私は少しこの問題を解決する方法について迷ってしまいました..

+1

@Pixieの答えが働きます。 –

答えて

69

あなたは、リソースのURIを開くためにContentResolverを使用する必要があります。

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

また、あなたは、このメソッドを使用してファイルやコンテンツのURIを開くことができます。

+0

次の場合、MalformedUrlExceptionが発生します。 Uri path = Uri.parse( "android.resource://se.javalia。 – Roland

+0

'Uri.parse()'がこの例外をスローしてはならないので、それは変です。 'Uri'を解析すると、それは奇妙です – Michael

+0

@Rolandこれはうまくいきます。 –

25

これは、あなたが本当に必要なものです:

上記に基づいて
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

これは何らかの許可が必要ですか?私はこれを使用できません – lirui

+1

私はそうは思わない。エラーは何ですか? – 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; 
} 

- 任意のリソースのための微調整バージョン:

/** 
* 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; 
} 

いくつかの情報:

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> 

ソース:

紛争

この答えが正しい、しかし、最終的なフィールドの一部ではありません - それは答えに関係ないR - ボリスTreukhov

@BorisTreukhov - u「は、最終的なフィールドの一部が正しくありません」によって何を意味するのか、私たちにを詳しく説明して下さい - 質問 - へのURIを取得するにはどのように...?それを解析できる方法を構築する(どのように解析するのですか?答えを参照してください)

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

素晴らしいです。ありがとうございます –

+0

この答えは正しいですが、最終的なフィールドに関する部分はありません。答えとは関係ありません。 –

+0

@BorisTreukhov - – ceph3us

関連する問題