In a situation where you are getting a response from an API, but there are some additional data (images, descriptions, etc.) that are lacking in the response and you need to add them. If the data that you want to add is small in size you can store that data inside the APK and add them dynamically.

For example you are getting the response from the API, a news article. The article has and id, a title and content, but it lacks an image and a description, and you need to show a list of news articles in RecyclerView. The id of the news article is an int for example.  In the Adapter class, in the bind method, where you are setting the values of your layout view elements, you are lacking a value for the image and the description TextViews in the RecyclerView item. You got this resources stored inside your APK, but the question is how to add them dynamically for each item of the RecyclerView.

First you will need to name this values accordingly for easier use. I have named them with a combination of underscore and the id value of the article, so that I will know which of the resources (image/drawable or a string) is for which item. Next you will need to get the id of the stored resource(image/drawable or string) in your APK and set the resource with that id for the item in the RecyclerView. To get the id of a resource you need to use the getIdentifier() method that has three parameters: the name of the resource, the type of the resource and your package name.

To dynamically add an image from the drawable resources in your APK you will add the code in the bind method in your Adapter class:

To dynamically add a string from the string resources in your APK you will add the code in the bind method in your Adapter class:

This will not be something that you will need to use often. But in a situation where you use an API that you have no control of, in means of what kind of response are you getting, and you want to add some additional data, that wont affect to much the size of your APK, I hope you will find this way very useful.

Happy coding!

 

 

Spread the love

Leave a Reply

Your email address will not be published.