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.
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.
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.
You can find strings. xml file inside res folder under values as shown below.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With