dynamically getting all image resource id in an array - android

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)

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

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.

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 add an Image to ImageView dynamically from a JSON array

I want to add an image to my iamgeview from the link stored in a JSON file that looks like this:
{
"parts":[
{"name": "Bosch Iridium",
...
...
...
"image": "R.drawable-hdpi.plug_boschi"
},
Right now I pull the link and display it with this code:
try {
jObject = new JSONObject(sJSON.substring(sJSON.indexOf('{')));
JSONArray pluginfo = jObject.getJSONArray("parts");
JSONObject e = pluginfo.getJSONObject(position);
String imagefile = e.getString("image");
Drawable image = getDrawable(imagefile);
ImageView itemImage = (ImageView) findViewById(R.id.item_image);
itemImage.setImageDrawable(image);
} catch (JSONException e) {
e.printStackTrace();
}
}
I'm pretty sure that this part is correct
ImageView itemImage = (ImageView) findViewById(R.id.item_image);
itemImage.setImageDrawable(image);
But I need help with the part above that which is getting the link from the JSON array so I can display it.
You need to get first the resource ID from the string contained in the JSON.
String imagefile = e.getString("image");
String resName = imagefile.split("\\.")[2]; // remove the 'R.drawable.' prefix
int resId = getResources().getIdentifier(resName, "drawable", getPackageName());
Drawable image = getResources().getDrawable(resId);
What you want to do is to look at the Resources class.
getIdentifier (String name, String defType, String defPackage);
So, basically parse the object to find the text plug_boschi, and call:
int resid=Context.getResources().getIdentifier ("plug_boschi", "drawable", null);

Android: How can I make a Drawable array?

How can I make an array that handles some of my images so that I can use it like this?:
ImageView.setImageResource(image[1]);
I hope I explained well...
To do that, you don't want an array of Drawable's, just an array of resource identifiers, because 'setImageResource' takes those identifiers. How about this:
int[] myImageList = new int[]{R.drawable.thingOne, R.drawable.thingTwo};
// later...
myImageView.setImageResource(myImageList[i]);
Or for a resizable version:
ArrayList<Integer> myImageList = new ArrayList<>();
myImageList.add(R.drawable.thingOne);
// later...
myImageView.setImageResource(myImageList.get(i));
First of all you have to get all drawable IDs of your pictures with the following method:
int android.content.res.Resources.getIdentifier(String name, String defType, String defPackage)
For example, you could read all drawable IDs in a loop:
int drawableId = resources.getIdentifier("picture01", "drawable", "pkg.of.your.java.files");
picture02...
picture03...
..and then save them into an Array of Bitmaps:
private Bitmap[] images;
images[i] = BitmapFactory.decodeResource(resources, drawableId);
Now you are able to use your images as array.
with respect of #Bevor, you can use getResources() method instead of android.content.res.Resources like this:
ArrayList<Integer> imgArr = new ArrayList<Integer>();
for(int i=0;i<5;i++){
imgArr.add(getResources().getIdentifier("picture"+i, "drawable", "pkg.of.your.java.files"));
}
Usage:
imageView.setImageResource((int)imgArr.get(3));
Kotlin code:
initialize below class:
private var drawables: Array<Drawable>
initialize drawables in 1 line:
drawables = arrayOf(
model.getDrawable(R.drawable.welcome_1),
model.getDrawable(R.drawable.welcome_2),
model.getDrawable(R.drawable.welcome_3)
)
my model.getDrawable() is
fun getDrawable(id: Int): Drawable {
return ResourcesCompat.getDrawable(context.resources, id, context.theme)!!
}
set drawable to imageView
holder.imageView.setImageDrawable(drawables[position])
String[] arrDrawerItems = getResources().getStringArray(R.array.arrDrawerItems); // Your string title array
// You use below array to create your custom model like
TypedArray arrDrawerIcons = getResources().obtainTypedArray(R.array.arrDrawerIcons);
for(int i = 0; i < arrDrawerItems.length; i++) {
drawerItemDataList.add(new DrawerItemModel(arrDrawerItems[i], arrDrawerIcons.getResourceId(i, -1), i == 0 ? true : false));
}
drawerItemAdapter = new DrawerItemAdapter(this, drawerItemDataList);
mDrawerList.setAdapter(drawerItemAdapter);

Categories

Resources