When programming for Android sometimes you have to use static methods. But when you try to access you resources in a static method with getString(R.string.text)
you'll get an error. Making it static doesn't work.
Does anyone knows a good way around this? The resource files in Android are very helpful for creating things in different languages or making changes to a text.
One way or another, you'll need a Context for that... For static methods this probably means you need to pass along a Context when calling them.
One way is you can pass context to your static method. check this out it definitely works
The post below gives a tip for creating an
Application
class to save your current context. Your newApplication
class will then be accessible from any other static method.This is how I access resources from inside static methods. Maybe not ideal, but.
First, I extend Application and set some public static field(s), and create a method to initialise them:
And in my manifest I register the extended Application:
In my starter activity (MainActivity), I make a call to initialise the static resources:
Then anywhere in your project, after MainActivity.onCreate(Bundle b) has run, you can call static methods that access your specified static resources:
Pass in a
Context
(i.e.Activity
) instance as a parameter object to static method. Then invokegetString
on the parameter.You could use
Resources.getSystem().getStringArray(android.R.array.done);