Resources Not Found Exception in Android
There may be few newbies in Android programming having trouble understanding Resources Not Found Exception. So, I planned to explain it in this blog post and make the explanation as simple as I can.
Resources Not Found Exception is thrown when the Resource API's failed to locate the resource.
Let us go through an example to know in detail on why this exception is thrown.
In this example, consider there is a text view on the UI which is used to show numbers from 10 to 1 and let's say we used a CountDownTimer class to achieve this task.
If this was the code you've implemented, your app will crash when the onTick method gets executed for the first time.
If you take a look at the log cat, you can see the API thrown a Resources Not Found Exception complaining that it cannot find the Strig Id.
Resources Not Found Exception is thrown when the Resource API's failed to locate the resource.
Let us go through an example to know in detail on why this exception is thrown.
In this example, consider there is a text view on the UI which is used to show numbers from 10 to 1 and let's say we used a CountDownTimer class to achieve this task.
If this was the code you've implemented, your app will crash when the onTick method gets executed for the first time.
If you take a look at the log cat, you can see the API thrown a Resources Not Found Exception complaining that it cannot find the Strig Id.
Simply, What this means is that the Resource API looked for a String named remainingTimeInSec and it failed to find it. This is because remainingTimeInSec is defined as int, not a String and the reason the Resource API searched for a String is because text view's setText method only takes String. So, we need to make sure we are passing a String inside the setText method.
Instead of passing remainingTimeInSec to the setText method, pass String.valueOf(remainingTimeInSec). This will make sure, a String is passed to the setText method.
You can now successfully run the code. Not really, this time the app will crash when the onFinish method is called. If you understood the above explanation then you know why the app crashed and how to solve it.
If you failed to resolve the crash or failed to understand why the crash happened inside the onFinish method then go through the explaining again. Below is the final code that will run successfully and not throw Resources Not Found Exception.
So, next time you face this issue just check the type of the variable that you are trying to pass and the type of the variable that is expected.