Get drawable by string - android

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

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

How to convert Drawable into int and vice versa in Android

I want to convert Drawable into int and then vice versa.Basically I want to save Arraylist object into sharedPrefrence. For that purpose I have Implement Gson to Srtring convertion Method. If I use here Drawable instead of int then Gson String convertion take alot of time. so I want to use int instead of Drawable.
private List<AppInfo> apps = null;
public void setIcon(int icon) {
this.icon = icon;
}
apps.get(position).setIcon(mContext.getResources().getDrawable(apps.get(position).getIcon()));
Where AppInfo here is
public AppInfo(String appname, String pname, String versionName, int versionCode, int icon, int color) {
this.appname = appname;
this.pname = pname;
this.versionName = versionName;
this.versionCode = versionCode;
this.icon = icon;
this.color = color;
}
Here is source of Converting ArrayList of Custom object into String so that i can save it to SharedPrefrence.
Gson gson = new Gson();
apps.get(number).setColor(picker.getColor());
String JsonAppsdata = gson.toJson(apps);
System.out.println("Storing="+JsonAppsdata);
utility.StoreData(getApplicationContext(), JsonAppsdata);
Int -> Drawable:
Drawable icon = getResources().getDrawable(42, getTheme());
Drawable -> Int:
(I assume, that you're populating List<AppInfo> apps with app's whose icons are already in res/drawable folder of your app)
Once you set your R.drawable.app1 to ImageView, you can also give it a tag to identify the resource in the ImageView later:
ImageView appIcon1ImageView = (ImageView)findViewById(R.id.app_icon_1);
appIcon1ImageView.setImageDrawable(getDrawable(R.drawable.app1));
appIcon1ImageView.setTag(R.drawable.app1);
......
// Once you need to identify which resource is in ImageView
int drawableId = Integer.parseInt(appIcon1ImageView.getTag().toString());
If your icons are coming from server - the only way is to store them to disk and then re-load them. (or, better, rely on the already existing image-caching solutions like picasso)
UPD:
There's no direct way of converting Drawable into int, but in this particular case, it's possible to get the int, instead of Drawable from PackageManager:
ApplicationInfo applicationInfo = mContext.getPackageManager().getApplicationInfo(apps.get(position).getPname(),1);
int icon= applicationInfo.icon;
This is how we can fetch app icon and set it for an imageview.
applicationInfo=mContext.getPackageManager().getApplicationInfo(apps.get(position).getPname(),PackageManager.GET_META_DATA);
int icon= applicationInfo.icon;
Rsources resources=mContext.getPackageManager().getResourcesForApplication(applicationInfo);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.itemIcon.setImageDrawable(resources.getDrawable(icon,null));
}else
{
holder.itemIcon.setImageDrawable(resources.getDrawable(icon));
}
The only solution that worked for me was in the chat by #KonstantinLoginov, but instead of using:
val drawable = context.getPackageManager().getApplicationIcon(applicationInfo),
I passed in the packageName:
val drawable = context.getPackageManager().getApplicationIcon(packageName) which is String and can easily be passed around.

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

R.id.image to string in android

In my project I'm trying to display several image files by manipulating the filename of one of the images programatically.
ie, I may have:
filename.jpg, filename_top.jpg, filename_middle.jpg
I receive input of an drawable int and am trying to find the filename of the displayed image before manipulating this filename and trying to display the programatically generated filenames.. problem is that the manipulated filename does not display.
ie. there is something wrong with this:
imageView2.setImageResource(getImageId(this, namebottom));
Any ideas how getImageId can be modified to make setImageResource work properly?
The code would look something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bun = getIntent().getExtras();
int imagenumber = bun.getInt("imagenumber");
String extension = bun.getString("extension");
// int become a val from 0 to 20 (array size)
setContentView(R.layout.clickeditem);
final int[] imgIds = new int[{
R.drawable.image0,R.drawable.image1,R.drawable.image2,,,R.drawable.image20};
//The first image with id top in the layout is set ok:
ImageView imageView1 = (ImageView)findViewById(R.id.top);
imageView1.setImageResource(imgIds [ imagenumber ] );
// problem here:
//try to get the name of this file: ie: filename.jpg
// and then manipulate the filename:
String name = imageView1.getResources().getString(R.id.image0);
//try to convert this to the filename_middle.jpg
String namemiddle = name.replace(".jpg", "_middle.jpg");
imageViewt.setImageResource(getImageId(this, namemiddle));
//try to convert this to filename_bottom.jpg
String namebottom = name.replace(".jpg", "_bottom.jpg");
imageView2.setImageResource(getImageId(this, namebottom));
}
//where getImageId is defines as follows:
public static int getImageId(Context context, String imageName)
{
return context.getResources().getIdentifier("drawable/" + imageName,
null, context.getPackageName());
}
return context.getResources().getIdentifier("drawable/" + imageName,
null, context.getPackageName());
replace this by
return context.getResources().getIdentifier(imageName,
"drawable", context.getPackageName());

Categories

Resources