Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How do you access a string-array from strings.xml in a custom class?

Tags:

arrays

android

I'd like to get my string-array without extending Activity in my custom class. Is there a way to do this?

String[] foo_array = getResources().getStringArray(R.array.foo_array); will not work without extending Activity, so I need a work-around.

like image 946
Joseph Webber Avatar asked Oct 16 '13 15:10

Joseph Webber


People also ask

How do you access an array of strings?

We can access an array value through indexing, placed index of the element within square brackets with the array name. Declaration and initialization of string array in a single line: String array can also be declared and initialized in a single line. This method is more recommended as it reduces the line of code.

What is the use of string xml file in Android?

String. xml file contains all the strings which will be used frequently in Android project. String. xml file present in the values folder which is sub folder of res folder in project structure.In Android Studio, we have many Views such as TextView,Button,EditText,CheckBox,RadioButton etc.

In which folder can you find the string resource file strings xml?

You can find strings. xml file inside res folder under values as shown below.


1 Answers

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;    } } 
like image 96
Raghunandan Avatar answered Sep 20 '22 00:09

Raghunandan