web-dev-qa-db-ja.com

drawableに保存されている画像のURIを取得します

アプリケーションにサンプル項目をいくつか追加しているので、ユーザーが最初に見たときにそれほど空に見えません。サンプル項目のリストには画像が必要で、使用する画像はアプリケーションの/ res/drawable-folderに既に保存されています。

URIからアイテム画像をロードするメソッドがすでにあるので、/ res/drawable/myImage.jpgへのURIを取得したいのですが、正しく取得できないようです。

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

成功せずにURIのいくつかのオプションを試しました。 「Android.resource:// .....」にはプロトコル「file://」ファイルが見つからないことがわかりません

だから今、私はこれを修正する方法について少し迷っています。

54
Roland

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

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

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

86
Michael
/**
 * 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>

ソース:

[〜#〜] dispute [〜#〜]

この答えは正しいですが、最終フィールドに関する部分はそうではありません-それは答えとは何の関係もありません–Boris Treukhov

@BorisTreukhov-「最終フィールドに関する部分が正しくありません」-質問-どのようにURIを取得するのか...?解析可能な方法を構築します(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> { ... }
42
ceph3us

これは本当に必要なものです:

 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) );
29
xnagyg

文字列連結の代わりにUri.Builderを使用できます

 Uri imageUri = (new Uri.Builder())
    .scheme(ContentResolver.SCHEME_Android_RESOURCE)
    .authority(resources.getResourcePackageName(resourceId))
    .appendPath(resources.getResourceTypeName(resourceId))
    .appendPath(resources.getResourceEntryName(resourceId))
    .build()
4

最も簡単な答えは次のとおりです。Uri.parse(String goes here); //そのため、ドローアブルをそのブラケット内に収めるには、これを行うだけです。

Uri.parse(getResource().getDrawable(R.drawable.ic_launcher_background).toString());

それでおしまい。

0
Pokhraj Sah

コトリンの場合、

context.resources.getResourcePackageName(R.drawable.image_name)
0
devDeejay