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.

106 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. thanks a lot .. it's cool and exactly what I was looking for

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

    ReplyDelete
  6. Thanks bro this helped me a lot.

    ReplyDelete
  7. 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
  8. I got my problem -

    String resourceName = "R.id.bShots";

    it should be -
    String resourceName = "bShots";

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

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

    ReplyDelete
  11. Great, thanks!

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

    ReplyDelete
  13. 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
  14. 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
  15. 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
  16. 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
  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.
    iOS App Development Company
    iOS App Development Company

    ReplyDelete
  18. 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
  19. 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
  20. 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
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  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. Дээд чанар бол зүгээр л( đá ruby thiên nhiên ) санаатай биш юм. Энэ нь өндөр( đá ruby nam phi ) түвшний төвлөрөл, тусгай хүчин( Đá Sapphire ) чармайлт, ухаалаг ( đá sapphire hợp mệnh gì )чиг баримжаа, чадварлаг туршлага, ( đá ruby đỏ )саад тотгорыг даван туулах( bán đá sapphire thô ) боломжийг хардаг.

    ReplyDelete
  29. Thanks for sharing informative information

    Thanks
    Cpa offers

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

    ReplyDelete
  31. 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
  32. 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
  33. 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
  34. 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 agian

    court marriage in delhi ncr
    court marriage in delhi
    court marriage in noida
    court marriage in ghaziabad
    court marriage in gurgaon
    court marriage in faridabad
    court marriage in greater noida
    name change online
    court marriage in chandigarh
    court marriage in bangalore

    ReplyDelete
  35. Dynamic retreviewing source from android is helpful. For any type of course learning is software field visit cognex technology, lern AWS from us it is a best known cloud computing program in 2020.For AWS training in Chennai visit us here.

    ReplyDelete
  36. With Sanjay Baghela, your business Website is in safe hands. He and his team are the best SEO Expert in India the leading digital marketing field.
    Best SEO Expert In India
    Best Seo Company in India

    ReplyDelete
  37. Thanks for sharing this informations.
    artificial intelligence training in coimbatore

    Blue prism training in coimbatore

    RPA Course in coimbatore

    C and C++ training in coimbatore

    big data training in coimbatore

    hadoop training in coimbatore

    aws training in coimbatore



    ReplyDelete
  38. It was great to read your article. Read mine here
    Mirakee
    Framasphere
    Mundoalbiceleste

    ReplyDelete
  39. Great post you shared with knowledgeable info, i would definitely use this method. when users finding Buy Instagram Followers USA therefore here are best way to gain likes and followers.

    ReplyDelete
  40. Such a great post. It's a really nice blog post. I like this and its helpful for me and i appreciate your work. Buy Mumbai Instagram followers Are you looking for instagram followers. More details To contact us + 917339876756

    ReplyDelete
  41. Check out this Mi M365 Electric Scooter review if you are planning to buy an e-scooter

    ReplyDelete
  42. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

    Security Guard License
    Ontario Security License
    Security License Ontario
    Security License

    Thank you..

    ReplyDelete