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.

175 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
    Replies

    1. IntelliMindz is the best IT Training in Chennai with placement, offering 200 and more software courses with 100%
      Placement Assistance.
      SAP HR tranining chennai
      SAP HANA traning chennai
      SAP SCM traning in chennai
      SAP BO training in chennai
      SAP PP traning chennai

      Delete

    2. IntelliMindz is the best IT Training in Chennai with placement, offering 200 and more software courses with 100%
      Placement Assistance. Start learning with us intellimindz, and became an expert in sap mm training in Chennai.
      contact 9655877577 for more details.
      SAP MM training in Chennai
      SAP SD traning in chennai
      SAP FICO training in chennai
      SAP Ariba traning in chennai
      SAP ABAP traning in chennai

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

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

    ReplyDelete
    Replies
    1. Thanks for sharing amazing information keep posting!
      mangaowl

      Delete
  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.

    Android App Development Company

    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.

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

    ReplyDelete
  15. 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
  16. 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
  17. It was great to read your article. Read mine here
    Mirakee
    Framasphere
    Mundoalbiceleste

    ReplyDelete
  18. 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
  19. 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
  20. Check out this Mi M365 Electric Scooter review if you are planning to buy an e-scooter

    ReplyDelete

  21. Book Tenride call taxi in Chennai at most affordable taxi fare for Local or Outstation rides. Get multiple car options with our Chennai cab service
    chennai to bangalore cab
    bangalore to chennai cab
    hyderabad to bangalore cab
    bangalore to hyderabad cab
    kochi to chennai cab

    ReplyDelete
  22. Nice Blog!
    Facing error while using QuickBooks get instant solution with our QuickBooks experts.Dial +1-(855)533-6333 Quickbooks Enterprise Support Phone Number

    ReplyDelete
  23. Nice & Informative Blog !
    QuickBooks is an accounting software that gives you a broad platform to manage your accounting tasks. In case you find any technical issue in this software, dial QuickBooks Customer Service Phone Number 1-(855) 550-7546 for quick help.

    ReplyDelete
  24. Hey! Excellent work. Being a QuickBooks user, if you are struggling with any issue, then dial QuickBooks Error 1328 (855)756-1077. Our team at QuickBooks will provide you with the best technical solutions for QuickBooks problems.

    ReplyDelete
  25. Nice Post !
    Our team at Quickbooks Error Support Number very well understands your frustration and thus, provides you immediate technical solutions to exterminate QuickBooks problems during this on-going pandemic.

    ReplyDelete

  26. Iam so thrilled because of finding your alluring website here.Actually i was searching for Android.Your blog is so astounding and informative too..Iam very happy to find such a creative blog. Iam also find another one by mistake while am searching the same topicIOS Development.Thank you soo much..

    ReplyDelete
  27. Hey! What a wonderful blog. I loved your blog. QuickBooks is the best accounting software, however, it has lots of bugs like QuickBooks Error. To fix such issues, you can contact experts via QuickBooks Customer Service Phone Number

    ReplyDelete
  28. I enjoyed reading about your coding thoughts, I have a few thoughts myself. Some guys coded a PSN code generator and it's pretty cool... works for me.

    ReplyDelete
  29. https://brtiamerica.blogspot.com/2013/12/installing-print-driver-for-hp.html?showComment=1601129743449#c880941674498067109
    Chennai IT Training Center
    Artificial Intelligence training in chennai - Basically AI Artificial Intelligence is a programming which is created for robots to think and work on there own without the help of humans.

    RPA Training Institute in Chennai - RPA is useful in making complex decision by collaborating with Artificial Intelligence. And it will also contribute to the market of Big data and IOT. Join the Best RPA Training Institute in Chennai now.

    Load runner training in Chennai - Load runner is an software testin tool. It is basically used to test application measuring system behaviour and performance under load. Here comes an Opportunity to learn Load Runner under the guidance of Best Load Runner Training Institute in Chennai.

    ReplyDelete
  30. Artificial Intelligence training in chennai - Basically AI Artificial Intelligence is a programming which is created for robots to think and work on there own without the help of humans.

    RPA Training Institute in Chennai - RPA is useful in making complex decision by collaborating with Artificial Intelligence. And it will also contribute to the market of Big data and IOT. Join the Best RPA Training Institute in Chennai now.

    Load runner training in Chennai - Load runner is an software testin tool. It is basically used to test application measuring system behaviour and performance under load. Here comes an Opportunity to learn Load Runner under the guidance of Best Load Runner Training Institute in Chennai.

    apache Spark training in Chennai - Apache Spark is an open- source, Split Processing System commonly used for big data workloads. Learn this wonderful technology from and under the guidance of Best Apache spark Training Institute in Chennai.

    mongodb training in chennai - MongoDB is a cross platform document - oriented database Program. It is also classified as NO sql database Program. Join the Best Mongo DB Training Institute in Chennai now.

    ReplyDelete
  31. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support in this area. same as your blog i found another one Mobile Marketing .Actually I was looking for the same information on internet for Mobile Marketing and came across your blog. I am impressed by the information that you have on this blog. Thanks once more for all the details.

    ReplyDelete
  32. Thanks for the interesting content. I like your post and your blog is amazing.

    If you are interested in Video Downloader apps you can check my blog site. It is new and really informative.

    VidMate Movie Download

    ReplyDelete
  33. This blog was very nicely formatted; it maintained a flow from the first word to the last. Skyfall Leather Jacket

    ReplyDelete
  34. Thanks for sharing such useful information with us. I hope you will share some more info about your blog. Please keep sharing. We will also provide QuickBooks Support Number for instant help.

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

    ReplyDelete
  36. Great Post, checkout this amazing stuff:- best online tutoring websites

    ReplyDelete
  37. Hey! Nice Blog, I have been using QuickBooks for a long time. One day, I encountered QuickBooks Customer Service in my software, then I called QuickBooks Customer Service Phone Number. They resolved my error in the least possible time.

    ReplyDelete
  38. Appsinvo is a Top Hybrid App Development company in Swedenthat provide result-oriented web and mobile app solutions.
    Mobile App Development Company in France

    ReplyDelete
  39. Hello everyone, We are Children's Furniture – Bao An Kids. Surely when you come to this page, you are looking for a professional children's interior design and construction unit to help you advise and choose for your family and baby to have a perfect and comfortable living space. the safest. Thank you very much for trusting and wanting to accompany Bao An Kids. Phòng ngủ trẻ em

    ReplyDelete
  40. Make an iconic appearance wearing Ajax Warriors Vest at fair price.

    ReplyDelete
  41. Such an interesting article here.I was searching for something like that for quite a long time and at last I have found it here.
    Bill Goldberg Harley Davidson Jacket

    ReplyDelete
  42. Thats great post !! I like ur every post they always give me some new knowledge.

    VidMate | VidMate for PC |
    VidMate 2014

    ReplyDelete
  43. Order Psychedelic Online l Psychedelic shrooms l Mushrooms Micro-dosing USA, United Kingdom, Canada, Poland, Finland, Germany, Netherlands, Ireland, Greece, Italy, Russia, France, Peru, Portugal, Spain, Belgium. Shrooms, mescaline, mushrooms, DMT, LSD, CODEINE, KETAMINE, IBOGA, MDMA, MOLLY.

    We have put together a collection of psychedelics from different parts of USA and test them to make up a good list of products for our clients to consume.  Legal Psychedelics Online, where to buy shrooms online, Buy Psychedelics Online, where to buy magic mushrooms, and many more. Order Psychedelics from us online to acquire quality, legal and excellent products in the lives of our clients for a better and stress-free lifestyle. It is to be noted that we have a very discreet and secure end-to-end delivery system combined with the best growers of Legal Psychedelics Online USA, We are typically the most trusted connects of Psychedelic brands medication worldwide. We guarantee 100 percent client satisfaction and Money Back Guarantee. buy shrooms from us at very affordable prices. where to buy magic mushrooms and a magic mushroom grow kit.
    For more information visit here : https://psychedelicrangers.com

    We are a group of young enthusiasts who are out to blow the whistle on the magical healing powers of Psychedelics and all its other advantages by making this healing drugs available to everyone. We have experienced the powers of Psychedelics and we which to share this experience with everyone out there. We will try our best to help anyone in need. All our products have been tested and verified by all competent authorities
    Our blog post - Psychedelicrangers
    Contact us - Psychedelicrangers
    FREQUENTLY ASKED QUESTIONS - Psychedelicrangers
    Our Products - Psychedelicrangers
    shipping return policy - Psychedelicrangers
    Psychedelic Rangers Shop - Psychedelicrangers
    10G Top Quality DMT Crystal | Spirit Molecule | N,N DMT
    28G Dutch Champagne MDMA Crystal

    ReplyDelete
  44. Thanks For Awesome Content Check this Out:-

    Epson Printer Error 0X9a Occurs when paper jam, bent or damaged rails, or dislocated encoder strip in the printer. Our team provides online solutions 24/7 for Epson Printer Customers. Follow the link below.

    ReplyDelete
  45. Thats great post !! I like ur every post they always give me some new knowledge.
    VidMate 2017 | VidMate Online | VidMate download 2018

    ReplyDelete
  46. Great post I must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more. Pareto Analysis

    ReplyDelete

  47. Thanks for the interesting content. I like your post and your blog is amazing.
    If you are interested in Video Downloader apps you can check my blog site. It is new and really informative.

    utorrent pro mod apk free download

    ReplyDelete
  48. Your blog was absolutely fantastic! Large amount of great information which is often attractive some and the other way.Thanks.
    home services app development

    ReplyDelete
  49. Thankyou!
    Searching for hours, and i'm finally here..

    ReplyDelete
  50. B3 Bomber Jacket For Sale - Free Shipping and Best Deal
    Men consistently partial to skins and hides due to the fact the start of timethey utilized it to insure by themselves and safeguard them by your cold temperatures.
    Now shearling leather coats, Leather Bomber Jacket, Real Leather Jacket holds probably the best legacy , masculinity along with ruggedness to get a guys outer wear.

    ReplyDelete


  51. I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work.

    havanese puppies for sale
    teacup havanese puppy for sale
    havanese dog for sale
    teacup havanese puppy
    black havanese puppy for sale
    havanese puppy for sale
    mini havanese puppy
    chocolate havanese puppy for sale
    toy havanese puppy
    havanese puppy
    https://www.fluffyhavanese.com/

    chihuahua puppies for sale
    chihuahua puppies for sale near me
    pug puppies for sale
    pug puppies for sale near me
    All kittens adopted from royaltykitten.com Sphynx Cattery come with current vaccinations, dewormings, written sales contract, Two year health guarantee, health record, Spayed or Neutered, 30 days of free pet insurance for your kitten, and a kitten care package which includes food, litter and several surprises for you and your kitten.
    hairless cat for sale
    hairless cats for sale
    sphynx cat for sale
    sphynx for sale
    sphynx kittens for sale
    pomeranian puppies for sale
    pomeranian puppies for sale near me
    teacup pomeranian puppies for sale
    pomeranian puppy for sale
    pomeranian puppy for sale near me

    ReplyDelete
  52. Our the purpose is to share the reviews about the latest Jackets,Coats and Vests also share the related Movies,Gaming, Casual,Faux Leather and Leather materials available Robbie Reyes Jacket

    ReplyDelete
  53. Hey! Fabulous post. It is the best thing that I have read on the internet today. Moreover, if you need instant support for QuickBooks Error, visit at QuickBooks Customer Service Our team is always ready to help and support their clients.

    ReplyDelete
  54. What a gorgeous Great way to make it more refreshing!
    blackandgrey

    ReplyDelete
  55. Hey, it's really nice information to share here. Thanks for your blog, keep posting like this regularly. Thank you!
    Truck Alignment Services
    roadside assistance services
    Truck Alignment
    Trailer repair near me
    Truck towing near me

    ReplyDelete
  56. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously
    in their life, he/she can earn his living by doing blogging.Thank you for this article.
    moving services near me
    commercial movers near me
    house movers ontario
    self storage company

    ReplyDelete
  57. Hey there
    This blog depicts exactly what I have been searching for hours, Thanks for sharing this

    Try - Zinzo - Online Grocery Shopping app to get groceries at lowest prices

    ReplyDelete

  58. Yazınızı okumak harikaydı. Harika yazı stili Uydu Servisleri İstanbul istanbul uydu servisi türksat uydu güncelleme 2022,
    uydu kurulumu uydu Montajı tv tamiri,
    merkezi uydu anten, çanak anten, tv tamir servisi, Teknik servis iptv,

    ReplyDelete
  59. Manufactures of Automatic water level controller and Indicator in Chennai and Tamilnadu, wireless water tank level indicator and wireless water level controller in Chennai, OMR, Anna Nagar, Velachery.

    ReplyDelete
  60. Fantastic blog i have never ever read this type of amazing information. chris martin jacket

    ReplyDelete
  61. Your article is detailed, thanks to it I solved the problem I am entangled. I will regularly follow your writers and visit this site daily. Download Whatsapp Aero Apk

    ReplyDelete
  62. Shreeja Oil Maker is a global leading manufacturer, wholesaler, supplier, exporter of various small scale machinery. Shreeja oil maker machine or Mini oil extraction machine is one of our innovative product which is able to extract 100% pure oil from the various seed. This is also known as a Oil Extraction Machine Manufacturer or mini oil Ghani. We have a stronghold in national as well as a worldwide market.

    ReplyDelete
  63. Hey! I am Gregory Gladiya. I am here from the technical team to assist you in resolving the Epson printer issues.For further information on on driver install, click here: Epson ET 2760 Driver. Here you will be able to find a solution to resolve issues that are faced with Epson printers of any model.

    ReplyDelete
  64. like to retrieve it,looking ahead to more subsidiary update and that i Already read your current post its brilliant thanks. VoiceMod Pro Cracked

    ReplyDelete
  65. Bigstar V2services Private Ltd is a well-known company that provides Security Services in Bangalore at a reasonable cost to its valued customers. We work with reputable multinational corporations, businesses, industries, banks, warehouses, flats, bungalows, showrooms, and hotels to provide security services. Our security experts are well-trained and dedicated at the time of need to defend our clients' property.

    ReplyDelete
  66. Satta king, satta king, Satta king 2020, Satta king up, Satta result, Satta king result, Satta king online, Gali result, Desawar result, Satta king chart

    ReplyDelete
  67. सट्टा किंग
    Disawer Result Today: दिल्ली से चलने वाले सट्टा मटका मार्केट (Satta Matka Market Delhi) के सबसे ..

    ReplyDelete
  68. Great Piece of content shared by you ! thanks
    DO check ma website Factsride.com

    ReplyDelete
  69. Interview power agreement over guess weight. Natural never how case mind it. At or level picture.religious

    ReplyDelete
  70. I really liked your point about, I've been struggling with this myself, so I'll definitely be trying out your tips."
    bus rental Dubai

    ReplyDelete
  71. Excellent post; this article has given me more information. With gratitude
    Adf training institute in kphb

    ReplyDelete
  72. Total Knee Replacement is a surgical procedure that involves replacing a damaged or worn knee joint with an artificial implant. It is a common treatment option for people suffering from severe knee pain and limited mobility. If you're experiencing knee pain, consider consulting with Lenin Ortho hospital for an evaluation and personalized treatment plan.
    Knee Replacement Surgeon in Chennai - Dr. Lenin's Orthoinde Hospital is a pioneer in total knee replacement and revision surgery.
    Knee Replacement Surgeon in Chennai | Dr.Lenin’s Orthoinde Hospital

    ReplyDelete
  73. Unlock cloud mastery with Explore Data Integration with Azure Data Factory Training in Hyderabad. Get certified and elevate your IT career to new heights today

    ReplyDelete
  74. This is fantastic information! Visiting your site is truly amazing and delightful. Thank you for sharing such valuable insights; they are incredibly helpful to me.

    SAP FICO Training in Hyderabad

    ReplyDelete