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

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

Related

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

Android: Enable certain button with id as index

I have 50 styled buttons with identificators like "level_i", I need to enable button with certain i in id.
I have code to work with indexed aarays in string xml, but I have no proper ideas how to change it for my usage
Class<R.id.array> res;
Field field;
try {
res = R.array.class;
field = res.getField("words_" + fname);
//set myString to the string resource myArray[fname,y]
myString = getResources().obtainTypedArray(field.getInt(null)).getString(y);
}
catch (Exception e) {
e.printStackTrace();
}
I believe you are saying that you have an ID resource named "words_" + fname for example R.id.words_100. If that is correct, then you can first get the ID using the name of the resource with getIdentifier. Then you can get the actual ID, then you can find the view with that ID:
String resName = "words_" + fname";
Resources res = getResources();
int resId = res.getIdentifier(resName, "id", getPackageName());
View button = findViewById(resId);
EDIT:
Modified original answer to fetch resources from R.id rather than R.string-array.

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

dynamically getting all image resource id in an array

there are many images in drawable foder so instead manually creating array of all image resource ids , i want to get all images dynamically of drawable folder in array.
currently i m using this code:
for(int i=1;i<=9;i++)
{
int imageKey = getResources().getIdentifier("img"+i, "drawable", getPackageName());
ImageView image = new ImageView(this);
image.setId(imgId);
image.setImageResource(imageKey);
image.setScaleType(ImageView.ScaleType.FIT_XY);
viewFlipper.addView(image, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
imgId++;
}
but in that code i need to manually edit the image name to get the resource id but i want to get all image with any name..
you can Use Reflection to achieve this.
import the Field class
import java.lang.reflect.Field;
and then write this in your code
Field[] ID_Fields = R.drawable.class.getFields();
int[] resArray = new int[ID_Fields.length];
for(int i = 0; i < ID_Fields.length; i++) {
try {
resArray[i] = ID_Fields[i].getInt(null);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
resArray[] now holds references to all the drawables in your application.
Well, If your image names are img1, img2 and so on, then you can create a variable like
String url = "drawable/"+"img"+i;
int imageKey = getResources().getIdentifier(url, "drawable", getPackageName());
you can also replace your getPackageName() method by your package name like "com.android.resource"
Simply,the general function is
public int getIdentifier(String name, String defType, String defPackage)

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