1

Is there a way to dynamically add values to an Android resource string-array?

E.g.:

    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="titles">
    </string-array>
</resources>
3
  • What is your use case? You could simply build the string array list in code and pass it where needed. Commented Apr 11, 2016 at 23:31
  • @bond I want to store some data, and I'm wondering if there's an easier way such as writing to a resource xml file rather than using a database Commented Apr 11, 2016 at 23:36
  • 1
    if it is a small list, you could save it in shared preferences. See developer.android.com/reference/android/content/…, See, putStringSet() method. Also another alternative would be to use something like Realm db if you rather save objects. www.realm.io Commented Apr 11, 2016 at 23:38

2 Answers 2

6

Is there a way to dynamically add values to an Android resource string-array?

No, because resources are read-only at runtime.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes! you can create a static array of strings in Android but dynamically adding values to an Android resource is not yet possible. It turns out that it’s easy to create and use a static array of strings in Android. Of course, you can do this in Java code, as I describe in my Java string array tutorial, but for Android, I’m talking about doing this in XML.

In short, this is how you define a static string array in an Android XML file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="my_books">
        <item>Scala Cookbook</item>
        <item>Play Framework Recipes</item>
        <item>How I Sold My Business: A Personal Diary</item>
        <item>A Survival Guide for New Consultants</item>
    </string-array>
</resources>

Then inside an Activity, Fragment, or other Java class, you can create a string array in Java from that XML like this:

Resources res = getResources();
String[] myBooks = res.getStringArray(R.array.my_books);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.