phnmnn
phnmnn

Reputation: 13250

android.content.res.Resources$NotFoundException. Module, aar library

I have library module with string resource. string.xml

<string name="lib_ver">1.0</string> 

and method:

public static String getLibVersion(Context context){
        return context.getResources().getString(R.string.lib_ver);
}

In my app application i include my module like aar library. Everything work properly except 1 thing. if i try to get lib version with lib method in activity class: getLibVersion(getApplicationContext()) i get error:

android.content.res.Resources$NotFoundException: String resource ID #0x7f02105b

But if i do in activity class, without call to library method:

getApplicationContext().getResources().getString(R.string.lib_ver)

There is no errors. Where is a problem? Thx.

Upvotes: 0

Views: 659

Answers (2)

phnmnn
phnmnn

Reputation: 13250

just need to update gradle to 2.1.2

classpath 'com.android.tools.build:gradle:2.1.2'

Upvotes: 1

Smit
Smit

Reputation: 2138

getApplicationContext: Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component. From android

That might be the reason that your ApplicationContext is throwing error! :)

More info: Context and ApplicationContext are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.

If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.

The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.

But in general, use the activity context unless you have a good reason not to.

Upvotes: 0

Related Questions