Tarikhelian Tarikhelian - 7 days ago 6
Android Question

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

Answer

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;