Resources Not Found Exception only when running on specific devices - android

I'm getting a crash in the Android Studio emulator and in the Google PLay Pre-Launch checks for just oe device.
The resource listed defintely exists in my source - it is in the drawable folder rather than any specific dpi folder - and it is found on all other devices I've tried my app on, that is emulator devices, Pre-launch Test devices and a couple of physocal devices.
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/ic_amalfi_pro_link.xml from drawable resource ID #0x7f080071
The main differences that I can see with teh device that is failing is that it is lower resolution - hence me checking that the vector drawables are in teh drawable folder, not a specific dpi folder.
The crashing device is also API 19 whereas the working devices are later versions. (I get a similar crash for a different resource that I haven;t fully investogated yet for API 21 in the Pre Launch teses).
Note that I have legacy support for vector drawables enabled in my build.gradle (app) with:
vectorDrawables {
useSupportLibrary true
}
I have tried a clean build - no change.
I have tried invalidating caches and rebuilding - no change.
I have tried changing the drawable for something else, changing back and rebuilding - no change.
I did have the same crash with a different drawable on teh same emulator test device and replacing that drawable with a differen drawable avoided that first crash and moved me oon to this next drawable causing the crash, so it does seem to e related to specific drawables - BUT the drawable IS there and does work on other devices.
This is so frustrating, I just don't know where else to look for the issue.
Update:
Following the content below requiring clarification regarding whether the vector drawable in question is used in any other activity I tested some more.
if I add the failing drawable to my main activity it works perfectly in my main activity but still fails to be found in the activity in which it causes the crash and still causes the crash
I appear to have at least three vector drawables in my project that are behaving the same way, in three different activities
if I replace the offending drawable in the crashing activity with another vector drawable (not one of the others that is causing a crash) then the activity in question does not crash.
if I replace the offending drawable in three crashing activity with one of the other offending drawables then the activity crashes reporting that the new offending drawable cannot be found.
I have checked the drawable XML and it is identical (other than the path details) to other vector drawables I am using on this project that do not cause the crash.

Starting with release 1.1.0-alpha01 of the AndroidX AppCompat library, there are "compat" attributes for compound vector drawables:
app:drawableTopCompat
app:drawableLeftCompat
app:drawableStartCompat
etc
You must be using AppCompatTextView to leverage these attributes. If your layout is inflated by a LayoutInflater built from an AppCompat theme, this will happen automatically when you use <TextView> tags. If not, you will have to explicitly specify them as <androidx.appcompat.widget.AppCompatTextView> tags.

I found the cause of the issue.
The crash was happening wherever a vector drawable was being used in a compound drawable.
There was nothing wrong with the drawables themselves, I just moved them out of the compound drawable and into their own ImageView within a LinearLayout to recreate the same effect.
A less efficient layout, but no crashes now.

Related

Android Studio, drawable is only available in debug mode

So I have a drawable that I am using in my project - it is a .png file I created using Aseprite, and I have quite a few of them. Some of the first ones I added seem to not be flagged as debug only, but many of the later ones are tagged as such. Attached is an example image of what I am talking about - is there any way to change the image to be available in release as well?
You added the drawable to use only in debug mode.Move that image to drawable root. Or Refactor > Move file and change the directory as follows (base directory of Drawable)

VectorDrawable Resources$NotFoundException while xml vector drawable resource file does exist

My app min SDK is 21 so its no need to add
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
to Application class since its only for lower than 21 (anyway I tried to add it with no result).
My build.gradle config file has
defaultConfig {vectorDrawables.useSupportLibrary = true}
setting and no proguard/minify enabled
debuggable true
crunchPngs false
minifyEnabled false
shrinkResources false
splits.abi.enable false
splits.density.enable false
Anyway I checked the compiled .apk file using AndroidStudio and insured that all my vector drawables are really present in res/drawable folder, so its not proguard/shrinker or like.
Also I have to mention that I'm using androidx instead of support in this project.
So I've tried all possible variations of image setting:
setImageResource(imgResId);
setImageDrawable(ContextCompat.getDrawable(context, imgResId));
setImageDrawable(AppCompatResources.getDrawable(context, imgResId));
setImageDrawable(VectorDrawableCompat.createFromResource(resources, imgResId));
setImageDrawable(VectorDrawableCompat.create(resources, imgResId, null));
setImageDrawable(ResourcesCompat.getDrawable(resources, imgResId, null));
without any result (actually the result was always an app crash). Sending real Theme instead of null did not help either.
It is a common PagerAdapter and vector drawable images are being set to corresponding ImageView on every page dynamically, so it's not that static xml android:src="#drawable\ic_img" case when you should (but not must) replace it with app:srcCompat="#drawable\ic_img".
And I also tried to wrap image into selector like:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/vector_image" />
</selector>
but no luck - crash report changes a bit but finally it leads to the same exception.
Nothing helped me from this SO question and any other SO questions I found as well.
My vector drawables are using gradient which works only starting from API 24. I'm testing my app on API 26 device but tried to replace all gradients by adding android:fillColor into the path section and commenting gradient section, like:
<path
android:pathData="M268.177,..."
android:strokeWidth="1"
android:fillType="nonZero"
android:strokeColor="#00000000"
android:fillColor="#FFEF5E32">
<!--<aapt:attr name="android:fillColor">-->
<!--<gradient-->
<!--android:startY="84.70677"-->
<!--android:startX="284.02185"-->
<!--android:endY="70.083954"-->
<!--android:endX="252.21419"-->
<!--android:type="linear">-->
<!--<item android:offset="0" android:color="#FFEF5E32"/>-->
<!--<item android:offset="1" android:color="#FFF68F32"/>-->
<!--</gradient>-->
<!--</aapt:attr>-->
</path>
And no luck...
I realize that importing my vectors to png/webp will most probably fix the issue but I want to use vector drawables.
When I was applying patch for gradient sections I noticed that AndroidStudio highlighted these gradient sections saying that it is supported from API 24 and my project min API is 21. So I have decided to check other warnings like:
Very long vector path (1456 characters), which is bad for performance.
Considering reducing precision, removing minor details or rasterizing
vector.
So I've started suspecting it as an issue source because there was an error message (red colored text) given in build window of AndroidStudio stating:
string too large to encode using UTF-8 written instead as
'STRING_TOO_LARGE'.
But there is no glue or pointing to source of this problem, its just states that I have a very long String somewhere in my project, so it could be preshipped realm database file for instance or something like.
Finally I found an anomaly in one of my vector drawables - it was a path string containing about 51k chars! Of course no warning was given to me at importing time (svg to xml, done using AndroidStudio).
Removing this path solved the crash issue but also a part of an image was lost.
So I've degrouped a problematic path group using Sketch and after importing it resulted in 2 paths of 19k and 24k chars, which is not good either, but it works now without any crash.
btw I am unable to find any information on string length limitations for vector/xml but gradle does apply this limitation at build time, so its known.
The limit of one xml string length revealed in this SO question and there is no official document on that could be found.

getDrawable returns null

Pff, this is one of these things that ruins your schedule, but you don't wanna give up. Since 2 days some of my bitmap resources don't load and show up in my app anymore. I nailed it down to the getDrawable() returning null on the supplied ResID.
I'm running this on Genymotion Nexus 5 with API 22, or a Nexus 5 physical device. For my project I mainly use the following to load drawables.
ResourcesCompat.getDrawable(context.getResources(), drawableID, null);
But because of this issue I also tried context.getDrawable(id) and getResources().getDrawable(id, getTheme()). Each method returns null.
Other things that might be interesting:
Resource is in my project (in mdpi, hdpi, xhdpi && xxhdpi)
file-name's are correct (xxx_yyy_zzz.png)
Clean project / deleted build products
Got old image files from my repo: Doesn't load
Resource have been copied and renamed: Doesn't load.
Open the resources in my Image Editor and saved as brand new files: Doesn't load.
Copied resources into empty dummy project: They actually show!
90% of my resources load perfectly, it's just a few larger bitmaps given issues.
The image does show in Android Studio Layout preview (Nexus 5, Api 22)
I've included some tests (like the copies), occasionally they actually load, but that's rare. The image I really care about never loads.
I also tried stepping into the Android Code and get these on getDrawable(id):
throw new IllegalStateException("Override configuration has already been set") (ContextThemeWrapper.java)
in AssetManager.java , getResourceValue I see a parameter being passed of type TypedValue with a string "res/drawable-xxhdpi-v4/{image_name}.png"
The latter raises some alarm bells as well, cause I don't have a folder with that -v4 suffix, so I wonder why it creates that. But stepping through that code in Android Studio doesn't really make sense to me as stepping into a method usually drops me right in a comment block of Android.
Anyway, I hope someone had some weird issues with image resources as well and might be able to point me in the right direction as to why this is happening. The fact that the image isn't corrupt and I really don't see anything wrong in my method calling or resources-folders, makes my kinda out of options.
Thanks in advance.
The only time this has ever happened to me was when I placed the image I was trying to load into my mipmap folder instead of the normal drawables folder.
When you begin typing R.drawable. can you see your drawable?

Android drawables are not recognized by AndroidStudio if I use dpi subfolders

I have just started the Treehouse Android development course, I have also asked this question on their forums without any luck.
DATA
AndroidStudio v 1.2.2, the course is based on v0.86 I think
OS / DE: Manjaro Linux, KDE
I have copied the image files inside the drawable folder, each into their specific dpi folder.
I have created the ImageView for a mail_title.png, and added the src as the full path to the png. When I do that, the image loads into the preview screen, and I can work with it, but If I try to build the app it just says the value of src cannot be a string.
So then I tried to point to it as a resource. On many forums and the android documentation I only found that I should reference it through a "pointer" #drawable/main_title , when I downloaded the projectfiles from the course I saw thats how they did it too.
If I try to rebuild now it gives the following error:
Error:(14, 22) No resource found that matches the given name (at 'src' with value '#drawable/main_title').
Then I tried to create a resource inside strings.xml, I found some autocomplete function that pointed me in "the right direction", of course it did not work!, same error as before. I have tried using absolute paths as well without luck.
Right now It shows R as "cannot resolve symbol R" in the MAinActivity file. I figured out by reading online that this is due to my drawable not existing problem.
Then I created a refs.xml in values and added
main_title.png
I actually tried with and without the extension (png)
After that I clicked on the IDE suggestion to create a drawable folder and it just created a #drawable folder inside of layout....
Basically it says it cannot resolve directory #drawable from activity_main.xml
and also
Error:(3, 33) String types not allowed (at 'main_title' with value 'main_title.png'). on the refs.xml file (this happens whether I use the extension (png) or not.
The only solution I have found is to just copy one version fo the images to the main drawables folder, and deleting all of the subfolders, if I don't delte them then it also doesn't work...
So, as you can see I'm kinda lost... Any help would be appreciated. I'm a python backend developer and I'm pretty comfortable usiong Pycharm (IntelliJ for python), but somehow I feel Android Studio has me totally lost!
So, in case anyone wonders, I solved it following both Cris and Rob advices. I installed appcompat v7 and put my img resources (png,jpd, etc) directly inside my drawable folder. Then I created a folder for each dpi resolution inside the res folder, NOT inside the drawable folder.
I use eclipse but i think its pretty much the same, you should have you various drawable folders, then you have to include the R (res folder)
import com.example.project.R;
and then call them by reference
R.drawables.main_title
Note you dont need to specify which drawable folder , adroid does that for you.
Also if you are getting unresolved errors with R then you may need to have the appcompatv7 library inlcuded in your project.

Resources NotFoundException?

I'm getting crash reports from android marketplace:
android.content.res.Resources$NotFoundException: Resource ID #0x....
I get about 17 of these a week. It's pointing me to the following in my code:
context.getResources().getDrawable(R.drawable.foo);
That resource is definitely present in my /drawable folder. I have several hundred thousand installs, I'm not sure how this could be failing for some users, but working for the vast majority. I'd like to find out what's going on, because they can't use the app in this state. Any ideas?
Thanks
--------- Update ----------------------
Also I can see the entry for the drawable in question in my R.java file, looks like:
public static final int foo=0x7f020034;
I do a clean build of the project, then straight after that do my release build (no code modification in between to give the automatic eclipse build stuff possibly let the R file go awry)
Thanks
I got this exception:
Resources$NotFoundException: String resource ID
when I was using setText with an int value. I had to convert it to String.
Before:
myTextView.setText(obj.SomeIntProperty);
After:
myTextView.setText(String.valueOf(obj.SomeIntProperty));
Is the crash reports coming from version <=1.6, and you have certain resources only in qualified folders, i.e. "drawable-mdpi" instead of just "drawable"? If so then read about "Known issues" at the bottom of this page.
The same problem I found on my application today morning and found a very simple solution to this. the problem looks big and complicated but it's not.
Steps which I followed are
Delete the bin folder it self
Clean the project
Remove application from your device
Run the application and check your scenario.
According to me it should not give this exception again.
Reason : When you build the application R.java contains all the memory address and it happens that those address are invalid for next run.
Second Reason : When you have the application which supports lanscape and portrati mode both and if you have not wrote the XML file for either of them then it's the possibility that may lead to this kind of crash. and there are pretty much chances of OutoFmemory and Memory leak issues when you have to support both the modes. please think on this as well.
This have occurred several times especially on phones with low density. I also noticed that it mostly happens with 9-patch images.
My solution was to include 9-patch images in as much density resource folders as I could (mdpi, ldpi, hdpi, xdpi).
You have included certain codes that reference content from Android SDK.
For example, I faced a similar issue once and when I removed the line
android:background="?android:attr/actionBarItemBackground"
from my xml, everything works fine again.
Heh, no idea, I'm actually working on a similar issue, but it could be it. It's worthwhile mentioning that while the device can upscale resources and layouts, it cannot downscale them. So if you have minimum values, set them in the AndroidManifest.xml. Try adding layout-ldpi and layout-small first.
A useful technique for logging which layout got loaded is to attach an android:tag to every root container of your layout XML file, and in onCreate() after setting setContentView(R.id.layout) just print the value of the tag. It will tell you which got loaded - you still have to plug the hole by adding all possible combinations, if just for debug purposes.
also, rename your drawables to drawables-nodpi folder to ensure no drawables are missing. this turns off internal scaling, makes APKs smaller and doesn't "pick" from any other drawable folder.
once you figure out whether it's the layout or drawable, additional metrics will help you find the root cause. for now, check the layouts first with "always use" drawables.
on monday when i get back to the office I'll post you the metrics code used to measure data captured in this thread - Which part of Android is in charge of picking a correct resource profile?
In my case I had a layout file that lead to the crash:
I got the following log-
That showed this link to my actual code:
Which is this line of code:
I checked my file navigator folder names as suggested by the most popular answer and it looked like the resource that is supposedly missing is in the normal layout folder
but when looking under the Project file navigator rather than the Android file navigator I was able to see that not only was the supposedly missing resource file not in the normal layout folder, but I didn't even have a layout folder without a special extension.
Adding an Android Resource Directory to the res folder and calling it layout and then pasting over the resources from your speciality folder (ex. layout-sw720dp) into it fixed the issue for me.
This solution will also work for other folders as suggested such as not having files in drawable and only having them in drawable-xxhdpi can be fixed by moving the file into drawable and tweaking it as needed. Good luck folder fiends!
This could also happen if the resource you are referring to (lets call it ResA) is in-turn referring to a resource which is missing (lets call it ResB).
Android will raise the ResourceNotFoundException for ResA even though whats really missing is ResB. Such is life!
In my case, ResB was defined in the values-swxxxdp but not in values. Hence I was getting this exception on phones but not on tablets.
The error can happen when portrait XML layout file is not defined. It doesn't happen all the time, but happens for example if user quickly turns off and on the phone, I suppose in that case the system calls the onCreate in portrait orientation, before calling onCreate in landscape.

Categories

Resources