- How to get string array from arrays.xml file in Java?
- Method 1: Using the Resources class
- Method 2: Using the XmlResourceParser class
- Method 3: Using the ArrayAdapter class
- Method 4: Using the TypedArray class
- How to get String Array from arrays.xml file
- Answer by Dakota Bauer
- Answer by Hope Gomez
- Answer by Zaylee Thornton
- Answer by Berkley Arias
- Answer by Araceli Meadows
- 5. Read String Value In Java Code.
- Answer by Bear Shields
- Answer by Israel Chen
- How to convert XML Node object to String in Java?
How to get string array from arrays.xml file in Java?
When working with Android development, it is often necessary to store arrays of strings in XML files, such as arrays.xml, and retrieve them in the Java code for use in the application. However, this can sometimes be a bit tricky and there are different methods for achieving this. Below are a few solutions for getting a String array from an arrays.xml file in Java.
Method 1: Using the Resources class
To get a String array from an arrays.xml file in Java using the Resources class, follow these steps:
Resources res = getResources();
String[] myArray = res.getStringArray(R.array.my_array);
public String[] getArrayFromResources() Resources res = getResources(); String[] myArray = res.getStringArray(R.array.my_array); return myArray; >
resources> array name="my_array"> item>Item 1item> item>Item 2item> item>Item 3item> array> resources>
And that’s it! You now have a String array from your arrays.xml file using the Resources class in Java.
Method 2: Using the XmlResourceParser class
To get a String Array from the arrays.xml file in Java using the XmlResourceParser class, follow these steps:
int resId = getResources().getIdentifier("arrays", "xml", getPackageName());
XmlResourceParser parser = getResources().getXml(resId);
int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) if (eventType == XmlPullParser.START_TAG && parser.getName().equals("string-array")) String[] stringArray = parseStringArray(parser); // do something with the string array break; > eventType = parser.next(); >
private String[] parseStringArray(XmlPullParser parser) throws XmlPullParserException, IOException ArrayListString> stringList = new ArrayList>(); int eventType = parser.next(); while (eventType != XmlPullParser.END_TAG || !parser.getName().equals("string-array")) if (eventType == XmlPullParser.START_TAG && parser.getName().equals("item")) String item = parser.nextText(); stringList.add(item); > eventType = parser.next(); > String[] stringArray = new String[stringList.size()]; stringList.toArray(stringArray); return stringArray; >
This method uses the XmlPullParser interface to navigate the XML document and extract the string array. It creates an ArrayList to store the string items, and then converts the ArrayList to a String array.
That’s it! With these steps, you can easily get a String Array from the arrays.xml file in Java using the XmlResourceParser class.
Method 3: Using the ArrayAdapter class
To get a String array from the arrays.xml file using the ArrayAdapter class, follow these steps:
- First, create an ArrayAdapter object by passing the context, resource ID of the array, and the layout file for the list item.
ArrayAdapterString> adapter = new ArrayAdapterString>(this, R.array.string_array, android.R.layout.simple_list_item_1);
String[] stringArray = getResources().getStringArray(R.array.string_array);
listView.setAdapter(adapter);
Here is the complete code:
ArrayAdapterString> adapter = new ArrayAdapterString>(this, R.array.string_array, android.R.layout.simple_list_item_1); String[] stringArray = getResources().getStringArray(R.array.string_array); listView.setAdapter(adapter);
Note that the R.array.string_array refers to the resource ID of the array in the arrays.xml file. The android.R.layout.simple_list_item_1 is the layout file for the list item.
That’s it! You have successfully retrieved a String array from the arrays.xml file using the ArrayAdapter class.
Method 4: Using the TypedArray class
To get a String Array from the arrays.xml file in Java using the TypedArray class, you can follow these steps:
- Create a TypedArray object by calling the getResources() method on the current context and passing in the resource ID of the array you want to retrieve.
TypedArray array = getResources().obtainTypedArray(R.array.my_array);
String[] myArray = new String[length];
- Loop through the TypedArray and add each element to the String array using the getString() method.
for (int i = 0; i length; i++) myArray[i] = array.getString(i); >
Here’s the complete code example:
TypedArray array = getResources().obtainTypedArray(R.array.my_array); int length = array.length(); String[] myArray = new String[length]; for (int i = 0; i length; i++) myArray[i] = array.getString(i); > array.recycle();
In this example, we assume that the resource ID of the array we want to retrieve is «my_array». You can replace it with the actual resource ID of your array.
How to get String Array from arrays.xml file
Here is my Java file:,Here is my arrays.xml file,Here is array.xml file,You can’t initialize your testArray field this way, because the application resources still aren’t ready.
package com.xtensivearts.episode.seven; import android.app.ListActivity; import android.os.Bundle; import android.widget.ArrayAdapter; public class Episode7 extends ListActivity < String[] mTestArray; /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); // Create an ArrayAdapter that will contain all list items ArrayAdapteradapter; mTestArray = getResources().getStringArray(R.array.testArray); /* Assign the name array to that adapter and also choose a simple layout for the list items */ adapter = new ArrayAdapter( this, android.R.layout.simple_list_item_1, mTestArray); // Assign the adapter to this ListActivity setListAdapter(adapter); > >
Answer by Dakota Bauer
How to get String Array from arrays.xml file ,I am just trying to display a list from an array that I have in my arrays.xml. When I try to run it in the emulator, I get a force close message. ,Your array.xml is not right. change it to like this,it works, but when I use
If I define the array in the java file
String[] testArray = new String[] ;
String[] testArray = getResources().getStringArray(R.array.testArray);
package com.xtensivearts.episode.seven; import android.app.ListActivity; import android.os.Bundle; import android.widget.ArrayAdapter; public class Episode7 extends ListActivity < String[] testArray = getResources().getStringArray(R.array.testArray); /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); // Create an ArrayAdapter that will contain all list items ArrayAdapteradapter; /* Assign the name array to that adapter and also choose a simple layout for the list items */ adapter = new ArrayAdapter( this, android.R.layout.simple_list_item_1, testArray); // Assign the adapter to this ListActivity setListAdapter(adapter); > >
Here is my arrays.xml file
- first
- second
- third
- fourth
- fifth
Answer by Hope Gomez
I am just trying to display a list from an array that I have in my arrays.xml. When I try to run it in the emulator, I get a force close message. ,Your array.xml is not right. change it to like this,it works, but when I use ,You can’t initialize your testArray field this way, because the application resources still aren’t ready.
If I define the array in the java file
String[] testArray = new String[] ;
String[] testArray = getResources().getStringArray(R.array.testArray);
package com.xtensivearts.episode.seven; import android.app.ListActivity; import android.os.Bundle; import android.widget.ArrayAdapter; public class Episode7 extends ListActivity < String[] testArray = getResources().getStringArray(R.array.testArray); /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); // Create an ArrayAdapter that will contain all list items ArrayAdapteradapter; /* Assign the name array to that adapter and also choose a simple layout for the list items */ adapter = new ArrayAdapter( this, android.R.layout.simple_list_item_1, testArray); // Assign the adapter to this ListActivity setListAdapter(adapter); > >
Here is my arrays.xml file
- first
- second
- third
- fourth
- fifth
Answer by Zaylee Thornton
Here is my Java file:,Here is my arrays.xml file,You can’t initialize your testArray field this way, because the application resources still aren’t ready.,If I define the array in the java file
If I define the array in the java file
String[] testArray = new String[] ;
String[] testArray = getResources().getStringArray(R.array.testArray);
package com.xtensivearts.episode.seven; import android.app.ListActivity; import android.os.Bundle; import android.widget.ArrayAdapter; public class Episode7 extends ListActivity < String[] testArray = getResources().getStringArray(R.array.testArray); /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); // Create an ArrayAdapter that will contain all list items ArrayAdapteradapter; /* Assign the name array to that adapter and also choose a simple layout for the list items */ adapter = new ArrayAdapter( this, android.R.layout.simple_list_item_1, testArray); // Assign the adapter to this ListActivity setListAdapter(adapter); > >
Here is my arrays.xml file
- first
- second
- third
- fourth
- fifth
Answer by Berkley Arias
string[] array = Resources.GetStringArray (Resource.Id.qarrays);,string[] array = Resources.GetStringArray(Resource.Array.array_questions);,The resource ID I have given the string array doesn’t show up in the C# code.,Then, you can access it same as below: String[] temp = Resources.GetStringArray(Resource.Array.languages);
- Is this question one?
- Is this question two?
- Is this question three?
- Is this question four?
Answer by Araceli Meadows
The content of strings.xml like below. The root XML element is resources. Each string XML element has a name attribute, this name is used in other XML or java source code files to get the string value.,Just use @string/string_value_name to refer to the string value in other XML files such as the layout.xml file. Below is an example.,Easy to remember. You can give the string value of a meaningful name, then refer to the string value by the name in the source file.,Easy to maintain. If you want to change the string value, just need to change the value in strings.xml, do not need to change each source file.
The content of strings.xml like below. The root XML element is resources. Each string XML element has a name attribute, this name is used in other XML or java source code files to get the string value.
Show Selection Input Favorite Car Name
5. Read String Value In Java Code.
String defaultInputText = getResources().getString(R.string.auto_complete_text_view_car);
Show Selection Input Favorite Car Name - Audi
- BMW
- Benz
- Ford
- Toyota
- Tesla
- Honda
- Hyundai
String carArr[] = getResources().getStringArray(R.array.car_array);
Answer by Bear Shields
For small apps you can put your string array in the usual res/values/strings.xml file, but in larger apps your static string array doesn’t have to be declared in the strings.xml file; you can put your array in any XML file in the res/values directory, as long as it has the format shown.,I was just working through an Android “Preferences” example, and saw where the author defined two static string arrays in a file named res/values/array.xml, like this:,Java: How to find the longest String in an array of Strings,In summary, if you needed to see how to define a static string array in XML in an Android app, I hope this example is helpful.
In short, this is how you define a static string array in an Android XML file:
- Scala Cookbook
- Play Framework Recipes
- How I Sold My Business: A Personal Diary
- A Survival Guide for New Consultants
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);
I was just working through an Android “Preferences” example, and saw where the author defined two static string arrays in a file named res/values/array.xml, like this:
- Headings
- Headings and Details
- All Data
- 1
- 2
- 3
Instead of accessing his string arrays in Java code, he access them in XML in a ListPreference , like this:
Answer by Israel Chen
XML file saved at res/values/ids.xml:,XML file saved at res/values/integers.xml:,TalkBack evaluation examples,Complex XML resources
How to convert XML Node object to String in Java?
Nowadays when everyone use JSON instead of a heavy XML for web communication this problem might be a little bit obsolete but, believe me, sooner or later you will be struggling with this one just like I was.
The main solution you will find in the internet is to use Transformer class that comes with Java in javax.xml.transform package.
import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; private static String convertNodeToString(Node node) < try < StringWriter writer = new StringWriter(); Transformer trans = TransformerFactory.newInstance().newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); >catch (TransformerException te) < te.printStackTrace(); >return ""; >
This solution should work in most cases but it is not perfect. When you are processing whole XML document from root you will probably don’t have any issue, however when you try to parse a single Node extracted from XML document you might get errors like:
javax.xml.transform.TransformerException: java.lang.RuntimeException: Namespace for prefix 'xxxxxx' has not been declared. at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:737) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:343)
This is because Transformer requires XML document to be well-formed and all namespace prefixes, used in Node, must be declared.
To get rid of such errors I’ve created a function that can read Node element and generate XML string without checking namespaces. You can use it and adapt to your needs. Keep in mind it is very simple, parse only three type of nodes:
- Node.DOCUMENT_NODE, - Node.ELEMENT_NODE, - Node.TEXT_NODE.
import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public static void getXMLString(Node node, boolean withoutNamespaces, StringBuffer buff, boolean endTag) < buff.append("<") .append(namespace(node.getNodeName(), withoutNamespaces)); if (node.hasAttributes()) < buff.append(" "); NamedNodeMap attr = node.getAttributes(); int attrLenth = attr.getLength(); for (int i = 0; i < attrLenth; i++) < Node attrItem = attr.item(i); String name = namespace(attrItem.getNodeName(), withoutNamespaces); String value = attrItem.getNodeValue(); buff.append(name) .append("=") .append("\"") .append(value) .append("\""); if (i < attrLenth - 1) < buff.append(" "); >> > if (node.hasChildNodes()) < buff.append(">"); NodeList children = node.getChildNodes(); int childrenCount = children.getLength(); if (childrenCount == 1) < Node item = children.item(0); int itemType = item.getNodeType(); if (itemType == Node.TEXT_NODE) < if (item.getNodeValue() == null) < buff.append("/>"); > else < buff.append(item.getNodeValue()); buff.append("") .append(namespace(node.getNodeName(), withoutNamespaces)) .append(">"); > endTag = false; > > for (int i = 0; i < childrenCount; i++) < Node item = children.item(i); int itemType = item.getNodeType(); if (itemType == Node.DOCUMENT_NODE || itemType == Node.ELEMENT_NODE) < getXMLString(item, withoutNamespaces, buff, endTag); >> > else < if (node.getNodeValue() == null) < buff.append("/>"); > else < buff.append(node.getNodeValue()); buff.append("") .append(namespace(node.getNodeName(), withoutNamespaces)) .append(">"); > endTag = false; > if (endTag) < buff.append("") .append(namespace(node.getNodeName(), withoutNamespaces)) .append(">"); > > private static String namespace(String str, boolean withoutNamespace) < if (withoutNamespace && str.contains(":")) < return str.substring(str.indexOf(":") + 1); >return str; >
- Node node - (org.w3c.dom.Node), - boolean withoutNamespaces - if true will remove all namespace prefixes, - StringBuffer - output XML document, - boolean endTag - should be set to true, this parameter is used in a recursive call.
This is how you can use it:
StringBuffer buff = new StringBuffer(); getXMLString(element, true, buff, true); System.out.println(buff.toString());