In an Android app I'm wirting, I have an HTML-like document in the resources. Unfortunately, I retrieve it in an XmlResourceParser object (using getResources().getXml(R.xml.texts), but I need to do significvant minipulation to it which I can only get in an org.w3c.dom.Document object. How can I convert it?
Related
I noticed that on the android developer page for getIdentifier it states:
Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
I'd like to try to avoid using it but my current implementation depends on it.
In my database I have hundreds of prepopulated entries, for each entry there are 3 associated string resources and an image. In order to access the resources via the entry, I save the resource names as strings in the tuple and then use getIdentifier to load them.
In case my implementation is confusing here are some pictures and example code:
string resources file
database table
Example Code:
coin = model.getSelectedCoin()!!
binding.topMedia.setImageResource(
resources.getIdentifier(coin.imageAddress, "drawable", requireContext().packageName)
)
binding.descriptionText.text = resources.getString(
resources.getIdentifier(coin.description,"string", requireContext().packageName)
)
Is this bad practice? Is there a more efficient implementation that allows me to connect my database entries with their resources?
You can get text resource from assets folder or from res/raw folder in two ways (let's assume your file name is product_json.json)
You can put a file with file name product_json in res/raw folder and access as below.
val inputStream: InputStream = resources.openRawResource(R.raw.product_json)
Or, you can put your file in assets folder (if not exist already then you're welcome to create one!) as access as below.
val inputStream: InputStream = assets.open(getString("product_json")
Note: assets.open("file_name_with_extension)e.g., assets.open("product_json.json")
Using point number 1 above is faster than accessing resources using val inputStream: InputStream = resources.openRawResource( resources.getIdentifier(getString(R.string.product_json), "raw", packageName) as getIdentifier() has to go through the iteration over all the string resources. This is very slow and not recommended, thus, IDE static analyzers show the warning of "Use of this function is discouraged because resource reflection makes it harder to perform build optimizations and compile-time verification of code. It is much more efficient to retrieve resources by identifier (e.g. R.foo.bar) than by name (e.g. getIdentifier("bar", "foo", null))". Using val inputStream: InputStream = resources.openRawResource(R.raw.product_json) is better because system has to just iterate over raw resources.
Perhaps you could be setting those values outside of a database? Create an object that describes your level, and define the image and description on that object using their resourceIds. Those are basically UI-related values, they shouldn't be in a database at all.
Can you create an XML object resource with key-value pairs (basically a hashmap) using an XML file analogous to arrays.xml? This would be an analogue of NSDictionary from Obj-C.
i.e.
<key>foo</key>
<value>bar</value>
I'd like for the value to be an array of strings, and I'd like to be able to copy and paste from XML files in my Obj-C projects.
Thanks.
A good alternative is to create JSON objects, and access these using GSON. If you already have a PList resource from an iPhone project, one way to convert to JSON is to create an object from the PList and write it to a JSON string file.
I have an XML file which I have retrieved the data via a Document variable. I need to extract data for a class which contains several fields. What is the easiest way to retrieve the records from the Document variable ?
For Document objet use DOM parser.
For XML files use SAX parser.
Try to use a SAX parser for XML parsing, because it is more memory efficient.
Hi
I am trying to fetch this xml response
<?xml version="1.0" encoding="utf-8"?>
<desc c="¥99"/>
but on my Android each time I get Â¥99 ,after parsing the xml, instead of correct data(i.e.¥99).Is there any way to parse this Currency data correctly.Please correct me if I am missing something.
EDIT:Here is the code that is used to get xml
docBuilder = docBuilderFactory.newDocumentBuilder ();
InputSource is = new InputSource ();
is.setEncoding ("UTF-8");
Document doc = null;
is.setCharacterStream (new StringReader (xmlStr));
doc = docBuilder.parse (is);
if (doc != null)
{
doc.getDocumentElement ().normalize ();
NodeList detail = doc.getElementsByTagName ("desc");
String c = detail.item (0).getAttributes ().getNamedItem ("c").getNodeValue ();
}
The answer depends on how you parse the XML. For instance, one of the overloaded Xml#parse() methods accepts an Xml.Encoding argument that you can use to specify that the source is UTF-8.
Other parsing methods likely have an option to set the encoding, as well. Just check the docs.
Of course, it's entirely possible that the server doesn't generate correct UTF-8, even though it's declared as such in the XML file.
It would help if we had the code where you are reading the XML stream.
I would assume that you need to ensure you're reading the stream in the correct encoding (as the stream reader may not take the XML declaration's encoding into account.
That doesn't look like well-formed XML. There is no attribute name, only the c element. That seems reason enough not to get correct results...
OK, with the example code, I'd guess it's the setCharacterStream() that fouls things up. Without having tested it myself, the docs say that encodings are used only by byte streams, so use setByteStream() instead, or, better use the byte stream constructor of InputSource.
Hi
Thanks for your support I recognized the problem ,the method in which I was getting response from server had below code
String strResponse = EntityUtils.toString (response.getEntity ());
where `response.getEntity ().getContentEncoding () returned null so I changed it to
String strResponse = EntityUtils.toString (response.getEntity (),"UTF-8");
where "UTF-8" is default charset.
Thanks StackOverFlow!
I am getting the value from a web server. I am getting the value as a string. Can anybody tell me how to convert the string to an xml file and where to store the xml file in android? And how do I access the file to parse the value, can anybody give an example?
Any help would be appreciated
Thanks in advance
In my understanding, Your meaning of "getting the value as string" is parse the content of InputStream. I think you don't have to parse the content and then convert the string to xml file, you can just use FileOuputStream to write the data in InputStream into file system.
You can use SAX or DOM to parse xml, they are both supported by android. See this post for more info.
Just pass the inputstream(response) from webserver to the Dom or Sax Methods no need to convert in to String