Boron
Boron

Reputation: 129

Access string-array resource programmatically and add value to it

I have an empty string-array resource in my strings.xml file like below:

<string-array name="categories"/>

I'm getting array of data from an API back which I need to populate onto a listview. Its ArrayAdapter takes in an @ArrayResource int for its resource like below:

public void showListViewDialog(…, @ArrayRes int arrayResource) {

    ...

    ListView listView = alertDialogView.findViewById(R.id.listViewCategories);
    ArrayAdapter arrayAdapter = ArrayAdapter.createFromResource(context,
            arrayResource, R.layout.custom_list_item);

    listView.setAdapter(arrayAdapter);

}

In my Java class, this is how I am retrieving the string-array resource:

List<String> categoriesToAdd= Arrays.asList(getResources().getStringArray(R.array.categories));

How can I then add the data back to it? I've tried the following but it does not work:

List<String> listCategories = new ArrayList<>();
listCategories.add(categoriesToAdd);

Upvotes: 0

Views: 1827

Answers (2)

Nabin Bhandari
Nabin Bhandari

Reputation: 16379

It is not possible to alter the string-array resource at run-time. So you cannot update it to show data in a ListView.

You don't need a string-array resource to create an ArrayAdapter. Instead, you can simply pass an ArrayList to its constructor to create it.

For example:

List<String> data = new ArrayList<>();

// sample data
data.add("Data 1");
data.add("Data 2");

final ArrayAdapter<String> adapter = new ArrayAdapter<>(this /*context*/,
        android.R.layout.simple_list_item_1, android.R.id.text1, data);

ListView listView = findViewById(R.id.listView);
listView.setAdapter(adapter);

Now if you want to add data to the list, use:

adapter.add("Data 3");

Upvotes: 2

Zaid Mirza
Zaid Mirza

Reputation: 3691

AFIK, Its not possible to change any resource files at runtime which bundled in APK. What you can do, just fetch your data from API and use it and if you want to save it for later use then save it in SharedPreferences file

Upvotes: 1

Related Questions