karse23
karse23

Reputation: 4115

It's possible to load R.drawable from resources passing a String parameter?

It's possible to load an image from resources passing to R.drawable a String?

I'm trying this:

public static Bitmap LoadBitmap(Context context, String filename)
{
     Bitmap image;
     image = BitmapFactory.decodeResource(context.getResources(), R.drawable.filename);
     return image;
}

Throws the following error:

filename cannot be resolved or is not a field

I'm trying to create the field in the R file creatic a constant but throws the following line:

R.java was modified manually! Reverting to generated version!

I'll appreciate your help or suggestions. Thanks

Upvotes: 2

Views: 6309

Answers (2)

Peter Knego
Peter Knego

Reputation: 80330

Resources can be accessed as raw data: use AssetManager.open(..). Just pass the filename of wanted bitmap (e.g. "drawable/myimage.png").

Then you can use BitmapFactory.decodeStream(..) to create a Bitmap from the data stream.

Update:

public static Bitmap LoadBitmap(Context context, String filename){
    AssetManager assets = context.getResources().getAssets();
    InputStream buf = new BufferedInputStream((assets.open("drawable/myimage.png")));
    Bitmap bitmap = BitmapFactory.decodeStream(buf);
    // Drawable d = new BitmapDrawable(bitmap);
    return bitmap;
}

Upvotes: 9

demented hedgehog
demented hedgehog

Reputation: 7538

@Peter Knego (not enough reputation to annotate the answer directly - stupid SO)

My (limited) understanding of the asset manager is that it allows access to files in the foo/assets dir. So the code from Peter would access:

foo/assets/drawable/myimage.png

I think @karse23 wants to know whether he can access images in the res/drawable dir:

foo/res/drawable/myimage.png

Why would you want to do this? Well if you want to access resources from an app and also 3rd-party apps. Ideally you do it using R from the app which owns the resource (so you can whack that ids in the layouts) and by name in the 3rd-party app (where you don't have access to the R class).

I'm trying to do just this and Peter's approach is referencing the assets dir in my code (but then again I'm accessing the assets in another package). (you can check this by logging the strings returned by the assetManager.list("")).

In support of Peter the doc says:

public final AssetManager getAssets ()
Retrieve underlying AssetManager storage for these resources.

which does seem to support the behaviour Peter is suggesting (maybe a bug in the old Android I'm using???).

In conclusion I think the solution is to whack the files in the assets dir and access them in the parent app from code :( (or do it the way the android dudes intended using a ContentProvider).

Upvotes: 0

Related Questions