Sunday, December 27, 2009

Dynamically Retrieving Resources in Android

Normally, when retrieving resources (drawables, strings, what have you) in code you use the automatically generated R.java to do so. However, I recently wrote a reference application wherein each item in a ListView has a different icon next to it. The data for all this is stored in JSON as an asset, which meant that there was no way for me to link my data to R.java.

Still, I needed some way to get a hold of the Drawable by name, and so I first turned to Resources.getIdentifier(). This method does the job well of finding the resource id of anything you desire, in any package:

Resources r = getResources();
int drawableId = r.getIdentifier("drawableName", "drawable", "com.mypackage.myapp");

This is all well and good, but: getIdentifier() is a general tool and as a result, slow. Running through 10,000 iterations, it took about 3200 ms on my G1. Also, it requires that you pass around a Context (or a Resources) wherever you need to use getIdentifier() which is an annoyance and seems unnecessary given that you can access R.java just fine normally in code.

The better solution - as long as you are retrieving data from your application's own R.java - is to use reflection.

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

In testing, the second method is about 5x faster than getIdentifier(). Not only that, but it means you don't have to pass a Resources object around to use it. Obviously this cannot be used if you're accessing resources outside of your application's permissions and you'll have to rely on getIdentifier() then.

One last note - simply linking to R.java is way faster than either of these two methods, so only fall back on these if you need to link to resource identifiers dynamically by name.

67 comments:

  1. Thanks a lot, you helped me on finding a solution that fitted my needs.

    Just note that in case you want to retrieve Views (Buttons, TextViews, etc.) you must implement R.id.class instead of R.drawable. It took me a while to find the error :)

    ReplyDelete
  2. I say thank you as well. It helped me very much

    ReplyDelete
  3. Thanx for the code, it helped me ver much....

    ReplyDelete
  4. it's reaaaaallly good...
    Thanks

    ReplyDelete
  5. thanks a lot .. it's cool and exactly what I was looking for

    ReplyDelete
  6. Yeah baby! Really you helped me! Thank you veeeery much :D

    ReplyDelete
  7. Thanks bro this helped me a lot.

    ReplyDelete
  8. Hi, thanx for the tutorial. I am having this error, can you help me out?


    09-18 20:46:05.960: E/MyTag(19018): java.lang.NoSuchFieldException: No field 'R.id.bShots' in class com.andrewschlie.bluelinestats.R$id


    But in R.java file, I have this -

    public final class R {
    .......
    public static final class id {
    ......
    public static final int bShots=0x7f080041;
    ......
    }
    }


    Here's my code that gets the error -

    String resourceName = "R.id.bShots";
    try {
    Class res = R.id.class;
    Field field = res.getField(resourceName);
    int resID = field.getInt(null);
    Log.d(TAG, "resID is " + resID);
    Button pn = (Button) findViewById(resID);
    pno.setOnClickListener(this);
    }
    catch (Exception e) {
    Log.e("MyTag", "Failure to get drawable id.", e);
    }

    ReplyDelete
  9. I got my problem -

    String resourceName = "R.id.bShots";

    it should be -
    String resourceName = "bShots";

    ReplyDelete
  10. Bingo! This is exactly what I needed. Time for this old C++ programmer to learn some reflection.

    ReplyDelete
  11. thank you man, you make my day ....

    ReplyDelete
  12. Great, thanks!

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

    iOS Training in Chennai
    Android Training in Chennai
    php Training in Chennai

    ReplyDelete
  15. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in android programming your post help me a lot.Thanks for your informative article. Android Training in velachery | Android Training institute in chennai

    ReplyDelete
  16. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    Android Training in chennai | Android Training

    ReplyDelete
  17. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your

    feed and I hope you post again soon.

    Android App Development Company

    ReplyDelete
  18. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.
    iOS App Development Company
    iOS App Development Company

    ReplyDelete
  19. Being new to the blogging world I feel like there is still so much to learn. Your tips helped to clarify a few things for me as well as giving..
    Fitness SMS
    Fitness Text
    Salon SMS
    Salon Text
    Investor Relation SMS
    Investor Relation Text

    ReplyDelete
  20. I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.

    Texting API
    Text message marketing
    Digital Mobile Marketing
    Mobile Marketing Services
    Mobile marketing companies
    Fitness SMS

    ReplyDelete
  21. I accept there are numerous more pleasurable open doors ahead for people that took a gander at your site.we are providing ReactJs training in Chennai.
    For more details: ReactJs training in Velachery | ReactJs training in chennai

    ReplyDelete
  22. HVO Vietnam Education Services Joint Stock Company was established in 2017 with the desire to bring a learning environment to maximize the creativity and logic of children through the subjects of the program. Home thinking math (Toán tư duy tại nhà ), Army summer camp (trại hè quân đội), Homeschool

    ReplyDelete
  23. Just seen your Article, it amazed me and surpised me with god thoughts that eveyone will benefit from it. It is really a very informative post for all those budding entreprenuers planning to take advantage of post for business expansions. You always share such a wonderful articlewhich helps us to gain knowledge .Thanks for sharing such a wonderful article, It will be deinitely helpful and fruitful article.
    Thanks
    DedicatedHosting4u.com

    ReplyDelete
  24. This is a nice Site to watch out for and we provided information on
    vidmate make sure you can check it out and keep on visiting our Site.

    ReplyDelete
  25. It is a very popular application which provides you to download videos, songs, mashups, remixes, trailers in your mobile , and off course in any quality. It contains many videos and of many types .
    like funny videos, motivational videos, songs lyrics, trailer and many more.
    Want to watch movie in slow connection,
    Vidmate app,
    Vidmate app to watch videos,
    vidmate,
    Vidmate Features,
    Vidmate Download,
    Multi sSource Downloader,
    cm security antivirus,
    leaked Movie Online,
    Why do people prefer Vidmate App.

    ReplyDelete
  26. This is a nice Site to watch out for and we provided information on
    vidmate make sure you can check it out and keep on visiting our Site.

    ReplyDelete
  27. Download and install Vidmate App which is the best HD video downloader software available for Android. Get free latest HD movies, songs, and your favorite TV shows.

    ReplyDelete
  28. Download and install Vidmate App which is the best HD video downloader software available for Android. Get free latest HD movies, songs, and your favorite TV shows.

    ReplyDelete
  29. Дээд чанар бол зүгээр л( đá ruby thiên nhiên ) санаатай биш юм. Энэ нь өндөр( đá ruby nam phi ) түвшний төвлөрөл, тусгай хүчин( Đá Sapphire ) чармайлт, ухаалаг ( đá sapphire hợp mệnh gì )чиг баримжаа, чадварлаг туршлага, ( đá ruby đỏ )саад тотгорыг даван туулах( bán đá sapphire thô ) боломжийг хардаг.

    ReplyDelete
  30. Thanks for sharing informative information

    Thanks
    Cpa offers

    ReplyDelete
  31. <a href="https://vidmate.vin/

    ReplyDelete
  32. Thanks for provide great informatic and looking beautiful blog, really nice required information & the things i never imagined and i would request, wright more blog and blog post like that for us. Thanks you once agianMarriage certificate in delhi
    Marriage certificate in ghaziabad
    Marriage registration in gurgaon
    Marriage registration in noida
    special marriage act
    Marriage certificate online
    Marriage certificate in mumbai
    Marriage certificate in faridabad
    Marriage certificate in bangalore
    Marriage certificate in hyderabad thanks once again to all.

    ReplyDelete
  33. Soma pill is very effective as a painkiller that helps us to get effective relief from pain. This cannot cure pain. Yet when it is taken with proper rest, it can offer you effective relief from pain.
    This painkiller can offer you relief from any kind of pain. But Soma 350 mg is best in treating acute pain. Acute pain is a type of short-term pain which is sharp in nature. Buy Soma 350 mg online to get relief from your acute pain.

    https://globalonlinepills.com/product/soma-350-mg/


    Buy Soma 350 mg
    Soma Pill
    Buy Soma 350 mg online



    Buy Soma 350 mg online
    Soma Pill
    Buy Soma 350 mg

    ReplyDelete
  34. Really i found this article more informative, thanks for sharing this article! Also Check here

    Download and install Vidmate App which is the best HD video downloader software available for Android. Get free latest HD movies, songs, and your favorite TV shows

    Vidmate App Download

    Vidmate apk for Android devices

    Vidmate App

    download Vidmate for Windows PC

    download Vidmate for Windows PC Free

    Vidmate Download for Windows 10

    Download Vidmate for iOS

    Download Vidmate for Blackberry

    Vidmate For IOS and Blackberry OS

    ReplyDelete