How to link database record with drawable id? - android

In my android application I have categories that stored in categories table of database. And I want to assign icons for each category. Category table looks like:
The problem is that I am not able to use drawable constants that defined in R file because they are not static and will be changed from build to build.
Is it correct to create public.xml file and define all drawable constants inside the file?
I am afraid that I can override some android constants using this approach.

Why don't you simply use the drawable names?
You can get the resource id at run time, for the given resource name and type.
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;
}
}
And use it like this:
int myID =
getResourceID("your_resource_name", "drawable", getApplicationContext());
Note: no path nor extension, in case of images.

I think you need this:
int imageResource = context.getResources().getIdentifier(imageName,
"drawable", context.getPackageName());
and if you want to set the image to an imageView:
// set the image
if (imageResource != 0)
yourImageView.setImageResource(imageResource);

Related

Use the address in the database for imageview

I'm sorry for my English .
I have a SQLite database of stored name of images in the drawable folder.
Example : R.drawable.image1 , R.drawable.image2 , ...
Is there a way that addresses stored in the database attributed to ImageViews?
Yes, you can get a Drawable by it's name, but it needs to be the full name of the resource, including the extension. So, for instance, if "R.drawable.image1" refers to an image named "image1.png", you will need to look it up by the string "image1.png".
Given the name of the image (e.g. "image1"), you can use the following method to get the resource id of the image (assuming that all of your images have the ".png" extension):
private final Map<String, Integer> iconMap = new HashMap<>();
public int getIconResourceId(final String imageName) {
String name = imageName.replace(".png", "");
Integer resourceId = iconMap.get(name);
if(resourceId == null) {
Resources resources = getResources();
resourceId = resources.getIdentifier(name, "drawable", getPackageName());
iconMap.put(name, resourceId); // cache the entry
}
return resourceId.intValue();
}
Note that the above code caches the resource ids - I use this in code for a RecyclerView, where the same image may need to be retrieved often, while scrolling the RecyclerView. If you don't need that, you may want to remove the HashMap.

how to work with images and database in android?

I have a quick question regarding to images stored in the drawable(s) folder and a database that has a table with image path. I am using sqlite and my images are png extension. How can I make it work with my database that has an image path and the R.drawable? How can I make a better use of my image path and assing the corresponding image to the corresponding record?
for example:
In my database, I have a table called deck and one of the column stores not a full path of the image but a partial path. Something like this:
Deck
---------------
/Allimages/lod/blueeyes.png
/Allimages/dk1/darkhole.png
.
.
.
( to N record)
the Allimages folder is stored within the drawable-ldpi folder. By the way, I have 6000 unique records in the table. What is the best approach for this problem?
the Allimages folder is stored within the drawable-ldpi folder.
This is not possible. You can't have subfolders in the drawable folders.
Store the images in a drawable folder like:
lod_blueeyes.png
dk1_darkhole.png
and so on.
Then, I'd store only the image names (without extension) in my db.
Then, I'd use a function to retrieve the images from the drawable folder:
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;
}
}
Usage: To retrieve the correct image
myImageView.setBackgroundResource
(
getResourceID
(
"my_image_name", "drawable", getApplicationContext()
)
);

Nullpointer when trying to find a string by ID

I'm using the below code to find a resource by id;
setContentView(R.layout.golders);
for (int i=1; i<hm.size()+1;i++)
{
int id = getStringIdentifier("Bus"+i);
view = (TextView)findViewById(id);
view.setText(hm.get(i).toString());
}
My getStringIdentifier() is working but when I try to set the text I'm getting a NullPointerException.
I've used the setContentView to focus on the golders.xml file which has the ids that I want to update.
I've tried Cleaning the project but that hasn't done anything either, any ideas?! Thanks!
EDIT:
public int getStringIdentifier(String aString)
{
String packageName = "com.example.bustimetable.Robbos";
int resId = getResources().getIdentifier(aString, "string", packageName);
return resId;
}
Your getStringIdentifier(String) method returns a string ID (something from R.string). You need a new method, something like getIdentifier(String), that will return soemthing from R.id. I can't see the XML, so I don't know what your TextView's ID is, but... you'll want to verify that the ID is, in fact, Bus_ where the _ is some number.
public int getIdentifier(String aString)
{
String packageName = "com.example.bustimetable.Robbos";
int resId = getResources().getIdentifier(aString, "id", packageName); // Get from R.id, not R.string
return resId;
}
The problem is that getStringIdentifier() is returning an id for a string resource. Apparently the id which is returned is not a valid id for a view resource. Even if was, I don't know how you can guarantee that you will get the view that you want. You need to either add another method to return id's for view resources, or modify the one you have so that it will return id's for either string or view resources

Drawable resource using a variable

I want to use a variable instead of R.drawable.myimage because I have a database with the image's names. I get the name from the database and I want to use the drawable resource with this name.
String flagimage = "R.drawable." + myHelper.getFlagImage(5);
int resourceId = Integer.parseInt(flagimage);
Bitmap flag = BitmapFactory.decodeResource(getResources(), resourceId);
You can use the name of a resource like
getIdentifier (String name, String defType, String defPackage);
getResources().getIdentifier("us","drawable","com.app");
The above function will return an integer value same as R.drawable.us.
This is how you access with resource names.
You can use this code to get the identifier...
Resources res = this.getResources();
int resID = res.getIdentifier(imagename, "drawable", this.getPackageName());

How do I get the resource id of an image if I know its name? [duplicate]

This question already has answers here:
Android, getting resource ID from string?
(14 answers)
Closed 2 years ago.
How do I get the resource id of an image if I know its name (in Android)?
With something like this:
String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
You can also try this:
try {
Class res = R.drawable.class;
Field field = res.getField("drawableName");
int drawableId = field.getInt(null);
}
catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
}
I have copied this source codes from below URL. Based on tests done in this page, it is 5 times faster than getIdentifier(). I also found it more handy and easy to use. Hope it helps you as well.
Link: Dynamically Retrieving Resources in Android
Example for a public system resource:
// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");
Another way is to refer the documentation for android.R.drawable class.
You can use this function to get a Resource ID:
public static int getResourseId(Context context, String pVariableName, String pResourcename, String pPackageName) throws RuntimeException {
try {
return context.getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
} catch (Exception e) {
throw new RuntimeException("Error getting Resource ID.", e)
}
}
So if you want to get a Drawable Resource ID, you can call the method like this:
getResourseId(MyActivity.this, "myIcon", "drawable", getPackageName());
(or from a fragment):
getResourseId(getActivity(), "myIcon", "drawable", getActivity().getPackageName());
For a String Resource ID you can call it like this:
getResourseId(getActivity(), "myAppName", "string", getActivity().getPackageName());
etc...
Careful: It throws a RuntimeException if it fails to find the Resource ID. Be sure to recover properly in production.
Read this
One other scenario which I encountered.
String imageName ="Hello"
and then when it is passed into
getIdentifier function as first argument, it will pass the name with string null termination and will always return zero.
Pass this
imageName.substring(0, imageName.length()-1)

Categories

Resources