Android: How Do You Access A String-array From Strings.xml In A Custom Class?


Answer :

Pass the context to the constructor of custom class and use the same

new CustomClass(ActivityName.this); 

Then

Context mContext; public CustomClass(Context context) {     mContext = context; } 

use the context

String[] foo_array = mContext.getResources().getStringArray(R.array.foo_array); 

Also keep in mind

Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)

http://android-developers.blogspot.in/2009/01/avoiding-memory-leaks.html

Also check this

android getResources() from non-Activity class

Edit:

Change this

public class CustomClass(Context context)  { } 

To

public class CustomClass {    Context mContext;    public CustomClass(Context context) // constructor     {     mContext = context;    } } 

try this,

Context context=getApplicationContext(); String[] foo_array = context.getResources().getStringArray(R.array.foo_array); 

And, do not use Activity Context as that is tied to the Activity life cycle.

Update,

getApplicationContext() is from Context class. That means any thing extended Context have this method. This also means you will be able to use this from service or from other resources.

But, if you custom class do not extend Activity/context, you have to pass Context as parameter to use getApplicationContext()

if you declare your activity like this

myMethod(Activity activity) //this is bad 

Bud if it is like following,

myMethod(Context context) //this is ok 

but from above declaration do not pass Activity or Service Context as they have own life cycle. instead you will use getApplicationContext()


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?