Skip to content Skip to sidebar Skip to footer

Android Get List Of String Resources From Special File

For example, i have my_string.xml file with strings: My string

Solution 1:

Put the file in the raw folder. Then you have to open the file

InputStreamin= getResources().openRawResource(R.raw.yourfile);

and parse the content manually, for instance save the list as xml or json and parse it and build your desired HashMap or whatever you like. Keep in mind that this may be a blocking operation and should not run on the main UI thread, run it async, but it depends on the length of the file you try to parse, but in general you should run that in an async thread

---- Update You could do something like this:

int stringRes[] = {R.string.my_string, R.string.another_string}
List<String> myStrings = new ArrayList<String>();
for (int id : stringRes){

   String str = getResources().getString(id);
   // TODO do some if check if you want to keep that string or whatever you want to ...
   myStrings.add(str);
}

you could store them into a HashMap(but getResources().getString() acts already like a HashMap ) or List

Solution 2:

If you want to access all the Strings from the strings.xml file you could use reflection on the R.string class.

Field[] fields = R.strings.class.getFields();
String[] allStringsNames = newString[fields.length];
for (int  i =0; i < fields.length; i++) {           
    allStringsNames[i] = fields[i].getName();
}

You can then store them in Hashmap or wherever you want

Solution 3:

The whole point of the XML file is to act as a "hashmap" kind of... you can always get a string by using context and the R.string reference. I'm assuming you are aware of this, so then you must be trying to create a simplified reference to this?

Creating a HashMap requires either static references (which are not available for XML) or a runtime creation of the list. You can create the list in the Application class, but I would caution against that. You may have trouble referencing the context but again, you can use the Application constructor to make sure you have a reference to context.

Beyond that, you should check into the StringArray resource. It does not allow you to reference a string using another string because it is an array. Here are the docs:

http://developer.android.com/guide/topics/resources/string-resource.html#StringArray

If it's super-important to use a HashMap then you should probably not use XML and should just create a static class. The XML resource files are primarily used for centralized data (to ease modifications to static strings) and, more so, multi-lingual purposes. Static HashMaps are not the proper use-case.

Post a Comment for "Android Get List Of String Resources From Special File"