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

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);
}

Related

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))
}

How can I convert String to Drawable

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

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

Select the resource for findViewById(R.id.xxx) in code

This is my first post, sorry for the title and the explication. Sorry for my English.
I define an .xml with all I need. I have 10 ImageView and the id for 10 ImageView are myimage01, myimage02, ... , myimage010.
I need to select an image for an ImageView.
I can do it as follows:
String imageName=getImageName();
id = getResources().getIdentifier(imageName, "drawable", getPackageName());
drawable = res.getDrawable(id);
ImageView cant1= (ImageView)findViewById(R.id.myimage01);
cant1.setImageDrawable(drawable);
ImageView cant2= (ImageView)findViewById(R.id.myimage02);
cant2.setImageDrawable(drawable);
ImageView cant3= (ImageView)findViewById(R.id.myimage03);
cant3.setImageDrawable(drawable);
ImageView cant4= (ImageView)findViewById(R.id.myimage04);
cant4.setImageDrawable(drawable);
ImageView cant5= (ImageView)findViewById(R.id.myimage05);
cant5.setImageDrawable(drawable);
ImageView cant6= (ImageView)findViewById(R.id.myimage06);
cant6.setImageDrawable(drawable);
ImageView cant7= (ImageView)findViewById(R.id.myimage07);
cant7.setImageDrawable(drawable);
ImageView cant8= (ImageView)findViewById(R.id.myimage08);
cant8.setImageDrawable(drawable);
ImageView cant9= (ImageView)findViewById(R.id.myimage09);
cant9.setImageDrawable(drawable);
ImageView cant10= (ImageView)findViewById(R.id.myimage010);
cant10.setImageDrawable(drawable);
But this is too bad, its better to use a loop. But I don't know do this.
I need something like that:
String cad;
for(int i=0;i<10;i++){
cad="myimage0";
String cat= Integer.toString(i);
cad=cad.concat(cat);
ImageView cant1= (ImageView)findViewById(R.id.cad);
cant1.setImageDrawable(drawable);
}
But there is an error in:
ImageView cant1= (ImageView)findViewById(R.id.***cad***);
Thanks for all
You can't directly pass in a String like that to findViewById. You'll need to look up the resource from your String first. Try this:
int idResource = getResources().getIdentifier(cad, "id", getPackageName());
ImageView cant1= (ImageView)findViewById(idResource);
Use this in a loop:
getResources().getIdentifier(resName, "id", getPackageName());
Where resName is exact string for that id (in your example, it's myimage01, myimage02, ...
so we have:
String cad;
for(int i=0;i<10;i++){
cad="myimage0";
String cat= Integer.toString(i);
cad=cad.concat(cat);
int id = getResources().getIdentifier(cad, "id", getPackageName());
ImageView cant1= (ImageView)findViewById(id);
cant1.setImageDrawable(drawable);
}

SetImageDrawable

Can someone please help with this. I am generating a random number and based on this random number I want to pick a png file from my res/drawable-mdpi folder to display. This is the code I'm using:
public void DisplayRandomPicture(int randomNumber)
{
String drawableName = "c"+ randomNumber;
ImageView image= (ImageView)findViewById(R.id.imageView1);
image.setImageDrawable(getResources().getDrawable(getResources().getIdentifier(drawableName, "res/drawable-mdpi", getPackageName())));
}
All the files in the res/drawable-mdpi folder start with "c". There is something wrong with the image.setImageDrawable syntax. When I run my app it crashes.
public void DisplayRandomPicture(int randomNumber)
{
String drawableName = "c"+ randomNumber;
ImageView iw= (ImageView)findViewById(R.id.imageView1);
resID = getResources().getIdentifier(drawableName, "drawable", getPackageName());
iw.setImageResource(resID);
}
Try above and make sure the image exists with the exact name.
I resolved this issue by using:
int id = getBaseContext().getResources().getIdentifier(drawableName, "drawable", getPackageName());
image.setImageResource(id);

Categories

Resources