I've got some ImageViews (~10) that I'd like manipulate in code. Instead of finding them line by line, I thought about looping and finding the views by the Resources.getIdentifier method. However it is discouraged according to the official documentation:
Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
Is there a faster, more efficient method available or would I be better off finding my views manually (without looping)?
Two alternatives I found so far! (let's assume your file name is product_json.json)
You can put a file with file name product_json in res/raw folder and access as below.
val inputStream: InputStream = resources.openRawResource(R.raw.product_json)
Or, you can put your file in assets folder (if not exist already then you're welcome to create one!) as access as below.
val inputStream: InputStream = assets.open(getString("project_json")
Note: assets.open("file_name_with_extension)e.g., assets.open("product_json.json")
Using point number 1 above is faster than accessing resources using val inputStream: InputStream = resources.openRawResource( resources.getIdentifier(getString(R.string.product_json), "raw", packageName) as getIdentifier() has to go through the iteration over all the string resources. This is very slow and not recommended, thus, IDE static analyzers show the warning of "Use of this function is discouraged because resource reflection makes it harder to perform build optimizations and compile-time verification of code. It is much more efficient to retrieve resources by identifier (e.g. R.foo.bar) than by name (e.g. getIdentifier("bar", "foo", null))". Using val inputStream: InputStream = resources.openRawResource(R.raw.product_json) is better because system has to just iterate over raw resources.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With