[SOLUTION] android.content.res.Resources$NotFoundException: String resource ID #0x1 in setText()

14Apr, 2019

This error is one of the very common issues developers come across during Android App Development.

Cause

This error occurs mostly when you pass an int value to the setText() method.  For example, when your code looks a bit like this:

or

The code above will throw the “android.content.res.Resources$NotFoundException: String resource ID” error.

So what really happens?

In Android Studio, there is a resource file called strings.xml located in res/values/strings.xml.  It is recommended that you should put common strings in this file.  One of the benefits of using this file instead of hardcoding your strings is that it makes it a lot easier to translate your App to multiple languages.  Bellow is an example of a strings.xml file:


<resources xmlns:tools="http://schemas.android.com/tools">
    <string name="app_name">Test App</string>
    <string name="copyright_notice">Copyright© 2018 Innomalist All Rights reserved.</string>
    <string name="connecting_server">Connecting Server…</string>
    <string name="drawer_header_unknown">Unknown</string>
    <string name="alert_ok">OK</string>
    <string name="alert_cancel">Cancel</string>
    <string name="message_exit">Are you sure you want to close app?</string>
    <string name="message_default_title">Message</string>
    <string name="message_loading_travels">Loading Travel List</string>
    <string name="title_travel">Travels</string>
    <string name="drawer_travels">Travels</string>
    <string name="drawer_edit_profile">Edit Profile</string>
    <string name="drawer_invite_friends">Send Invitation</string>
    <string name="drawer_support">Support</string>
    <string name="drawer_about">About</string>
    <string name="drawer_exit">Exit</string>
    <string name="drawer_options">Options</string>
    <string name="distance_traveled">Distance Traveled</string>
    <string name="time">Time</string>
</resources>

So the setText() method also accepts an int parameter.  The int parameter should be an id of one of the string resource.  For example:

The above code is valid and would not throw any error.

That said, anytime you pass an int value to the setText() method, the method assumes there is a string resource with that id.  When it does not find the id, the method throws the “android.content.res.Resources$NotFoundException:” exception.

Solution

Solving this exception is easy.  All you have to do is change the type of the parameter in the setText() method to String.  For example:

If you are working with a library or you simply do not have access to the variable declaration, then simply wrap the variable in String.valueOf(int).  For example:

The code above is my preferred method of solving this problem.

Feel free to ask any questions or contribute to this post in the comment section below :).


Leave a Reply

Your email address will not be published. Required fields are marked *