0

The following SO question how-can-i-assign-an-id-to-a-view-programmatically explains how to set id to views programmatically .My problem is slightly different. I would want to know if it is possible to set resource id/name to arrays programmatically.

    ArrayList<String> new_list = new ArrayList<>();
    String [] stringArray = {"foo", "bar"};

    for(String str:stringArray) {
        new_list.add(str);
    }
    /* This is a random example of doing things I  
     * certainly have more complex computation 
     * add more random item and convert it back to array
     */
    new_list.add("random_1");
    new_list.add("random_n");

    String [] updatedArray = new String[new_list.size()];
    updatedArray = new_list.toArray(updatedArray);

Resource ID is defined like

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="reservedNamedId" type="id"/>
</resources>

Now I want to do something like this

updatedArray.setID(R.id.reservedNamedId);

But that does not compile since array does not have a method setID like the Views class.

I understand if my string-array is defined in xml, I could use the name attribute to access it globally but what what I want is to programmatically create an array and assign a global name/id. So the basic intention was to define an array resource and make it available globally through resource id. Is it possible? Is it achievable in some other way?

Community
  • 1
  • 1
jazaman
  • 1,007
  • 3
  • 12
  • 30
  • 1
    `//not allowed since array does not have a method setID `. That is a confusing description. Better: `that does not compile`. – greenapps Aug 13 '16 at 11:42
  • i don't think so its possible what you are trying to do. this resource id is basically used to assign id's to components dynamically. –  Aug 13 '16 at 13:15
  • @greenapps thanks updated the post – jazaman Aug 13 '16 at 14:38

1 Answers1

0

The ids, which you are talking about, are not meant to be used for anything other than views or read-only data. I would recommend storing your array within the SharedPreferences or to pass it around inside a bundle associated with a intent.

The first approach could be realised with the following code:

SharedPreferences.edit().putStringSet("your_key", stringSet)
SharedPreferences.getStringSet("your_key", defaultSet) 

An introduction to the second approach can be found here (Passing ArrayList through Intent).

Community
  • 1
  • 1
Jacob
  • 493
  • 6
  • 17
  • Thanks @Jacob I thought about it and since there is no clearer way I might have to implement something similar but it defeats the purpose since my existing code base only handles arrays. – jazaman Aug 14 '16 at 17:09