Issue
I get a list of names from the database and I want to assign an image to each name.
I found that we can use int resID = getResources().getIdentifier(imgName , "drawable", getPackageName()); but there are few instances where I have to assign one image to different names.
In the above code you can get the resource id of the drawable by its name. But I don't want to store the same image with different names and also I don't want to use any arrays.
Is there any way to get a reference to drawable by the name we assign to it?
What I'm trying to do is keep the execution time as less as possible.
Solution
As stated in question comments, and for next users : I think the best solution is putting correspondances in a Hashtable.
Hashtable<String, Drawable> map=new Hashtable<>(SIZE);
//iterates for each couple key/name - drawable you need
map.put(KEY, drawable);
//then you can access to drawables easily with the name :
Drawable d=map.get(KEY);
All hashTable costs are linked to hastable data modification : adding elements, updating elements (and i'm not even sure for update), deleting elements. As your hash seems be fixed, there is litterally no costs (except memory usage) and access is almost[constant, not linear in size] as direct as if you were given the position in an array.
So i think that's the solution you need. You can have a drawable having multiple key, it's not a problem. However, one key leads always to ONE drawable.
Remember that map.put(); is not duplicating the value (the drawable here) except maybe if it is a primitive data. Therefore, any change to your drawable (if some changes happen) will be applied to all keys having the same drawable. That may not be an issue, but you must know that if you use hashtable for other usages.
EDIT : As you need this hashtable for each your fragments, you need to make an abstract class from whom each your fragment will inherit, and declare this hastable as protected in that class. Therefore, each subclass will be able to get it. You can also make this hashtable private, and implement a function "Drawable getDrawableFromName(String name)" returing the drawable from the hastable.
I heavily suggest you to have an abstract main subclass for your activities in case where you would need doing things like that in activities.
Answered By - Feuby
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.