How to convert Drawable into int and vice versa in Android - 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.

Related

Hardcoding Int reference as String to create JAR

I have a situation where I am creating JAR and I don't want to reference any of String or Int from /res/values. So I am hardcoding it everywhere
event_info.put("CLIENT_HALT", new EventInfo(R.string.client_halt, R.drawable.error, 0, EV_PRIO_HIGH, 0));
As you see "R.string.client_halt" refers to String "Halt" in res/values/abc.xml
But it is of type Int, hence I cannot do like this
event_info.put("CLIENT_HALT", new EventInfo("Halt", R.drawable.error, 0, EV_PRIO_HIGH, 0));
Below is EventInfo method
public EventInfo(int res_id_arg, int progress_arg, int priority_arg, int flags_arg)
{
res_id = res_id_arg;
//icon_res_id = icon_res_id_arg;
progress = progress_arg;
priority = priority_arg;
flags = flags_arg;
}
How do I overcome this issue and hardcode int value in my method. I tried below case but it won't work and give me "NumberFormatException"
String halt = "Halt";
int foo = Integer.parseInt(halt);
Thanks
By passing the id into constructor of your class, you can retrieve the string in the following way.
String stringValue = getResources().getString(R.string.client_halt);
If you are not able to get getResources() directly, pass the context in constructor and do the following
_context.getResources().getString(R.string.client_halt);

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

How to access Images form Drawable using Dynamic String Path

I have this type of image path
String img_path = "R.drawable."+lower+"_25";
lower contain dynamic name of images...
this images are already in drawable how to show images in my
ImageView in android
Make constructor in your adapter
public class MyAdapter extends XXXXXXX{
Context con;
public MyAdapter(Context con) {
this.con = con;
}
.
.
.
int id = con.getResources().getIdentifier(lower+"_25", "drawable", "<your package name>");
imageView.setBackgroundResource(image_id);
}
You can get the id of the image in the drawable using it's name, using:
int image_id = getResources().getIdentifier(lower+"_25", "drawable", getPackageName());
imageView.setBackgroundResource(image_id);
You can use:
getResources().getIdentifier(lower+"_25", "drawable", getPackageName())

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