How can I convert String to Drawable - android

I have many icon in drawable folder and I have their name as String. How can I access to drawable folder and change background imageView (or any view) use these name in dynamically. Thanks

This can be done using reflection:
String name = "your_drawable";
final Field field = R.drawable.getField(name);
int id = field.getInt(null);
Drawable drawable = getResources().getDrawable(id);
Or using Resources.getIdentifier():
String name = "your_drawable";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);
Then use this for setting the drawable in either case:
view.setBackground(drawable)

int resId = getResources().getIdentifier("your_drawable_name","drawable",YourActivity.this.getPackageName());
Drawable d = YourActivity.this.getResources().getDrawable(resId);

It can be done like this:
ImageView imageView = new ImageView(this);
imageView.setBackground(getResources().getDrawable(getResources().getIdentifier("name","id",getPackageName())));

Try this:
public Bitmap getPic (int number)
{
return
BitmapFactory.decodeResource
(
getResources(), getResourceID("myImage_" + number, "drawable", getApplicationContext())
);
}
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}

if you have the filename as string you can use:
int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());
with this id you can access it like always (assumed its a drawable):
Drawable drawable = getResources().getDrawable(id);

use case if not in any activity, using #FD_ examples
Note:
if you are not in any activity you have to send context param in order to use "getResources()" or "getPackageName()", and "getDrawable(id)" is deprecated, use getDrawer(int id, Theme theme) instead. (Theme can be null):
String name = "your_drawable";
int id = context.getResources().getIdentifier(name, "drawable",
context.getPackageName());
Drawable drawable = context.getResources().getDrawable(id, null);

Related

Android - getResources().getIdentifier replacement

In android I am looping through the database and assigning text and image:
Cursor res = myDb.getAllData();
while (res.moveToNext()) {
Actors actor = new Actors();
actor.setName(res.getString(1));
String th = res.getString(11);
Integer thumb = this.getResources().getIdentifier(th, "drawable", "mypackage");
actor.setThumb(R.drawable.th);
}
However Lint suggests not to use getIdentifier - Use of this function is discouraged because resource reflection makes it harder to perform build optimizations and compile-time verification of code.
In database column I have just the image name (string). How can I replace getIdentifier?
Even if I change the DB column maybe directly to R.drawable.imagename, it is still a string and for setThumb I need a drawable.
Ok, so the only solution what I've found is here https://stackoverflow.com/a/4428288/1345089
public static int getResId(String resName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
and then just calling:
int resID = getResId("icon", R.drawable.class);
This works very well, however some users reports, that after installing the app from Play store (not my app, but any with this method implemented and proguard enabled), after a while it will start throwing NoSuchFieldException, as more resources are mapped to the same class/field.
It can be caused by proguard but not sure. The solution is then to put the old way getResources().getIdentifier to the exception part of code.
You can try this approach:
Rename your resources as follow:
ressourceName00
ressourceName01
ressourceName02 .... and so on,
then use the methode below:
for (int i = 0; i < RessourceQtt; i++) {
Uri path1 = Uri.parse("android.resource://yourPackage Directories/drawable/ressourceName0" + i);
list.add(new CarouselItem(String.valueOf(path1)));
}
You can try this my code three way
// Show message and quit
Application app = cordova.getActivity().getApplication();
String package_name = app.getPackageName();
Resources resources = app.getResources();
String message = resources.getString(resources.getIdentifier("message", "string", package_name));
String label = resources.getString(resources.getIdentifier("label", "string", package_name));
this.alert(message, label);
set icon like that
private int getIconResId() {
Context context = getApplicationContext();
Resources res = context.getResources();
String pkgName = context.getPackageName();
int resId;
resId = res.getIdentifier("icon", "drawable", pkgName);
return resId;
}
this is also
//set icon image
final String prefix = "ic_";
String icon_id = prefix + cursor.getString(cursor.getColumnIndex(WeatherEntry.COLUMN_ICON));
Resources res = mContext.getResources();
int resourceId = res.getIdentifier(icon_id, "drawable", mContext.getPackageName());
viewHolder.imgIcon.setImageResource(resourceId);
I hope this code help for you.
public static int getIcId(String resN, Class<?> c) {
try {
Field idF = c.getDeclaredField(resN);
return idF.getInt(idF);
} catch (Exception e) {
throw new RuntimeException("No resource ID found for: "
+ resN+ " / " + c, e);
}}

Set image on a button where buttonname is coming from the database

In case I have to set an image on a button, programmatically, then I use the following code:
Drawable img;
ToggleButton tb_button = (ToggleButton) findViewById(R.id.tglButton);
img = ResourcesCompat.getDrawable(getResources(), R.drawable.p189, null );
tb_button.setCompoundDrawables(img,null,null,null);
Now the situation is that I have read the name of the image from a database into a variable. Thus lets assume that my variable has the following value:
String img_str= "p189";
Now how do I set the same image on the button when the image name is stored inside a variable.
use following method to get image from string.
private int getImageFromString(String name) {
int resId = getResources().getIdentifier(name, "drawable", getPackageName());
return resId;
}
You can create drawable resource id reference dynamically as follows
int resId=getResources().getIdentifier(img_str, "drawable", context.getPackageName())
img = ResourcesCompat.getDrawable(getResources(), resId, null )
and of course don't forget about try catch in case of wrong resource name
You can get drawable as follows by itss name,
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(imgName, "drawable", context.getPackageName());
return resources.getDrawable(resourceId);
So elaborating on what ABK said. You can get the the Drawable ResId and then use that to get the drawable within a function like this:
private Drawable getDrawableFromString(String name) {
int resId = getResources().getIdentifier(name, "drawable", getPackageName());
return getResources().getDrawable(resourceId);
}

Get drawable by string

I parse image name by json, and now for displaying I would have to get the drawable id by the image name so I can do this:
background.setBackgroundResource(R.drawable.eventimage1);
When I get the image name the format is like this:
image_ev1.png
Use this function to get a drawable when you have the image name. Note that the image name does not include the file extension.
public static Drawable GetImage(Context c, String ImageName) {
return c.getResources().getDrawable(c.getResources().getIdentifier(ImageName, "drawable", c.getPackageName()));
}
then just use setBackgroundDrawable method.
If you only want the ID, leave out the getDrawable part
i.e.
return c.getResources().getIdentifier(ImageName, "drawable", c.getPackageName());
this gets you your image id
int resId = getResources().
getIdentifier(your_image_name.split("\\.")[0], "drawable", getApplicationInfo().packageName);
if you need a drawable after that :
getResources().getDrawable(resId)
Add this method to your code:
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
Then retrieve your image so:
Context ctx = getApplicationContext();
background.setBackgroundResource(getResourceID("image_ev1", "drawable", ctx)));
For Kotlin programmer (ContextCompat from API 22):
var res = context?.let { ContextCompat.getDrawable(it,resources.getIdentifier("your_resource_name_string", "drawable", context?.getPackageName())) }
Your can also use e.g. "mipmap" instead of "drawable" if resource is place in other location.
Here is how to do in Kotlin :
// FilePath : ../drawable/app_my_bg_drawable.xml
// Call function as: val fileIntId = getDrawableIntByFileName(context, "app_my_bg_drawable")
fun getDrawableIntByFileName(context: Context, fileName: String): Int {
return context.resources.getIdentifier(fileName, "drawable", context.packageName)
}
// FilePath : ../drawable/app_my_bg_drawable.xml
// Call function as: val fileDrawable = getDrawableByFileName(context, "app_my_bg_drawable")
fun getDrawableByFileName(context: Context, fileName: String): Drawable? {
return ContextCompat.getDrawable(context, context.resources.getIdentifier(fileName, "drawable", context.packageName))
}

Android: How check if a image exists in a IF clause?

I need to know how check if an image exists in R.drawable, It has to be dynamic so I have to use a string that gives me the name of the image.
I've tried with '!=null' or exist but it hasn't worked.... Help please!!!!!!!!!
titulo=bundle.getString("titulo");
textView = (TextView) findViewById( R.id.textView1);
textView.setText(titulo);
foto="f"+bundle.getString("numero")+"a";
System.out.println(foto);
flipper =(ViewFlipper) findViewById(R.id.vfFlipper);
this gives me the name of the image a need...
image = new ImageView(this);
image= new ImageView(this);
image.setImageResource(R.drawable.f00a1);
image.setScaleType(ScaleType.FIT_CENTER);
flipper.addView(image);
Whith this I can use the image but i need to use the variable "foto" so it can be dynamic
Thanks!
Everything in the R class is an integer - you can't create a string to represent a resource id. The closest you can get is to use getResources() then call...
getIdentifier(String name, String defType, String defPackage)
...this will allow you to find the integer which represents your resource based on the resource name.
you could use getResources to get an instance of Resources class. In Resources class, you have getDrawable If the resource is not found, you would get ResourceNotFoundException which also means the image is not found.
so the code will be something like this
Resource r = getResources();
Bool fileFound = true;
Drawable d = null;
try{
d = r.getDrawable(your_image_id);
}
catch(ResourceNotFoundException e){
fileFound = false;
}
if(findFound){
// Your operations
// set drawable to your imageview.
}
Thank you all! i mix the two answers and .. it work!
Resource r = getResources();
Bool fileFound = true;
Drawable d = null;
try{
d = r.getDrawable(getIdentifier(foto1, "drawable", getPackageName());
}
catch(ResourceNotFoundException e){
fileFound = false;
}
if(findFound){
// Your operations
// set drawable to your imageview.
}
getResources().getIdentifier("icon", "drawable", "your.package.namespace");
check for non zero value for above statement.
if(0)
//does not exists
else
//exists
private boolean isDrawableImageExists(String imgName) {
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
return id != 0;
}

How to assign Image Resource to ImageView with String in Android

I am trying to create a routine that will assign a card image to an ImageView without using something like this: R.drawable.card_10clover. I would prefer to use a string, but the way I'm doing it doesn't work.
String imgRes = "R.drawable.card_";
int num = 10;
imgRes += "10";
String suit = "clover";
imgRes += "suit;
ImageView card = (ImageView) findViewById(R.id.imgcard);
card.setImageResource(imgRes);
Unfortunately setImageResource only takes an int. Please help.
Thank you,
Jack Blue
Use getIdentifier (String name, String defType, String defPackage);
Your imgRes does not need the prefix R.drawable
String imgRes = "card_";
int num = 10;
imgRes += "10";
String suit = "clover";
imgRes += "suit;
ImageView card = (ImageView) findViewById(R.id.imgcard);
int resourceId = getResource().getIdentifier (imgRes, "drawable", "com....");
card.setImageResource(resourceId);

Categories

Resources