I am parsing an XML file from assets folder to dump my data into the database. Later on i may fetch this and display it in a text view. But while parsing i am losing some data, ie, if i have some 50 words within the XML tags before parsing, in my database i am not able to find all of them after parsing.
For exmple:
I am parsing this line:
<about>Skandagiri also known as kalavara durga, is an ancient mountain fortess located approximately 70km from Banglore city and 3 km from Chikkaballapur in the Indian State of Karnataka.It is off Bellary road(NH 7, Hyderabad to Bangalore Highway) and overlooks Nandi Hills, Mudddenahalli and Kanive narayanapura.The peak is at an altitude of about 1350 meters</about>
after parsing in my database:
at an altitude of about 1350
i am using String to hold my parsed value like this:
if (element.equalsIgnoreCase("about")){
String str=parsedValue;
}
If you are using SAXparser than it is better to wrap the data with StringBuffer.
Take a look in oficial documentation : ContentHandler.
Here is the interesting part from it :
The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information.
Plaese try Below code..I think solved your issue.
Element element = (Element) node.item(i);
NodeList id = element.getElementsByTagName("about");
Element line1 = (Element) id.item(0);
if (null != line1)
AdsFound[i] = getCharacterDataFromElement(line1);
else
AdsFound[i] = "";
Use a StringBuffer, since text can be read in chunks and you may be reading just the part of code.
use string buffer and append all the chunks, so that finally you will get the complete text without missing out any data.
Like this:
StringBuffer strbufr = new StringBuffer();
if (element.equalsIgnoreCase("about")){
String str = strbufr.toString().trim();
}
#Override
public void characters(char[] ac, int i, int j) throws SAXException {
strbufr.append(ac, i, j);
}
Related
So I can add data to a data base just fine but when I try and add
test sentence
testing sentence two
to the data base then retrieve it I'm getting
test sentence testing sentence two
I'm adding the test data from a string with the enter already put in and there is no way in the code for me to ad \n into since I'm pulling data from a Textview into a string and saving to the database.
well actually you can try to add \n. read each character of the string and find the location of the RETURN character. then in new String copy contents before that character, then copy '\n' and then copy the rest of the content of the string.
here's the code:
public void onClick(View arg0) {
String s=ed.getText().toString();
int index=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)==10){
index=i;
}
}
String temp=s.substring(0, index);
temp=temp+'\n';
temp=temp+s.substring(index+1, s.length());
tv.setText(temp);
}
Here is what I am trying : I have a list of names. I want to search an XML file depending on that names.
XML looks like this :
<book>
<string> book name </string>
<array>
<string> Name1 </string>
<string> Name2 </string>
</array>
</book>
Now I want to search say "Name1" and if it matches I want to get the name of the book.
Is this possible? If yes can someone provide some code/snippet or maybe tell me the steps how I can do it. Thank you
Android has some built-in XML parsing functions. Take a look at http://developer.android.com/training/basics/network-ops/xml.html
Basically:
1) Set up an InputStream for the XML content (if you are downloading it, or reading it from a getResources() for example)
2) Set up your parser: XmlPullParser parser = Xml.newPullParser();
3) Start reading the XML in a loop. When parser.getName().equals("book"), then continue on until you get to your parser.getName().equals("string") and save the results of parser.getText(); Then when you continue on and hit parser.getName().equals("array") and you continue on again to parser.getName().equals("string"), then check the results of parser.getText() to see if it matches your search string.
Clear as mud?
Parsing XML is a lot harder than it was advertised to be 20 years ago or so, but once you understand that the parser reads the XML as it comes in, it makes it a little easier to see the overall picture of how to implement it. Study up on that link, it gives you everything you need to know.
There is a lot of ways to parse XML, I suggest you to use Jsoup
Its really easy to extract data from XML.
String html = "<?xml version=\"1.0\" encoding=\"UTF-8\">
<book>
<string> book name </string>
<array>
<string> Name1 </string>
<string> Name2 </string>
</array>
</book></xml>";
Document doc = Jsoup.parse(html, "", Parser.xmlParser());
Element book = doc.select("book").first();
Element bookName = book.getElementsByTag("string").first();
Elements array = book.getElementsByTag("array");
for (Element e : array.select("string")) {
//....
}
Thank you all for the answers. I am using the using the tutorial here and wrote this method to search the XML.
public List<String> search(String key, String url){
List<String> items = new ArrayList<String>();
XmlParser parser = new XmlParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName("book");
for(int i = 0; i<nl.getLength();i++){
Element e = (Element) nl.item(i);
NodeList n = e.getElementsByTagName("string");
if(parser.getElementValue(n.item(1)).equals(key) ||
parser.getElementValue(n.item(2)).equals(key) ){
items.add(parser.getElementValue(n.item(0)));
}
}
return items;
}
I am helping to develop an app for Android that uses special characters from different parts of the world at times, specifically when listing the names of people. So, a good example would be a Spanish or Swedish accent on a name. The app is not rendering these correctly. What do I need to add to web services so that these accent marks show correctly? They show correctly in my database, but not in the app.
Here is an example:
http://docs.oracle.com/javase/tutorial/i18n/text/string.html
String original;
original = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
When printed, the String named original appears as:
AêñüC
To convert the String object to UTF-8, invoke the getBytes
method and specify the appropriate encoding as a parameter.
The getBytes method returns an array of bytes in UTF-8 format. To
create a String object from an array of non-Unicode bytes, invoke the
String constructor with the encoding parameter. The code that makes
these calls is enclosed in a try block, in case the specified encoding
is unsupported:
try {
byte[] utf8Bytes = original.getBytes("UTF8");
byte[] defaultBytes = original.getBytes();
String roundTrip = new String(utf8Bytes, "UTF8");
System.out.println("roundTrip = " + roundTrip);
System.out.println();
printBytes(utf8Bytes, "utf8Bytes");
System.out.println();
printBytes(defaultBytes, "defaultBytes");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
The StringConverter program prints out the values in the utf8Bytes and defaultBytes arrays to demonstrate an
important point: The length of the converted text might not be the
same as the length of the source text. Some Unicode characters
translate into single bytes, others into pairs or triplets of bytes.
I have a database thats in the form of a text file, my job is to parse the txt file and display the data in a listview. I have no idea where to start.
Heres an example entry.
"|9251115|,|0|,|DETAILS|,||,||,|Heading Price Text Text |,||,||
Where each || represents a field. There are also html tags between heading price and the text (p,b)
My first idea would be to parse it similarly to an xml document, i.e have it create a new line where it starts with a "|", fill it with everything in between and end the line when it reaches the next "|". But I still have no concrete idea on how to do this.
EDIT:
Taking it one step at a time for now. Using stringtokenizer to read it line by line and remove "," for a start. Ran into a problem, the textview to display the results is displaying false for some reason instead of the scanned text. here's my code if anyone needs a good headscratcher.
Context myContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView t = (TextView) findViewById(R.id.text);
st = new ArrayList<property>();
try
{
InputStream is;
is = myContext.getAssets().open("rooms.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String read = br.readLine();
while( read != null)
{
StringTokenizer st = new StringTokenizer(read,",");
{
while(st.hasMoreTokens())
{
String a = st.nextToken();
String b = st.nextToken();
String c = st.nextToken();
String d = st.nextToken();
String e = st.nextToken();
String f = st.nextToken();
String g = st.nextToken();
String h = st.nextToken();
t.setText(a+" "+b+" "+c+" "+d+" "+e+" "+f+" "+g+" "+h);
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
While you can definitely implement your own parser using pure Java code, you should consider using a SQLite database (1) to store your data, which will allow you to insert, delete, modify and query much more easily.
If you database comes in that format from an external source, I'd write a one-time parser that parses the data and inserts it into the SQLite database for future use.
Remember that the CPU on Android devices is slower than your average PC CPU, so if you are parsing large amounts of data in this format all the time, your app might become very slow. Hence my suggestion of converting it to a database.
Another option you have in this case is using XML like you said, because there are ready-to-use parsers out there. But the advice about performance remains: you should really avoid reparsing the data all the time and, instead, store it in a ready-to-use format.
(1): http://developer.android.com/reference/android/database/sqlite/package-summary.html
Here is how I would do,
Have an object with getter/setter
Have a list intialized
1) You need to use StreamReaders/Bufferedreader to read the file
2) If each is not empty
2a) Use StringTokenizer to parse the string with "," as delimiter
2b) Set tokenized values to object
2c) Add object to list
3) return the list created in above step.
Note: If large data you need to be careful while reading entire file, you may get OutofMemoryError.
Bruno Oliveira gave very good advice.
You can parse your file by reading it line by line and then use string.split method, as result you will have all your data in an array where you can easily read and put into a list view or move it to a sqlite database.
I have a lengthy string in my Android program.
What I need is, I need to split each word of that string and copy that each word to a new String Array.
For eg: If the string is "I did android program" and the string array is named my_array then each index should contain values like:
my_array[0] = I
my_array[1] = did
my_array[2] = Android
my_array[3] = Program
A part of program which I did looks like this:
StringTokenizer st = new StringTokenizer(result,"|");
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
while(st.hasMoreTokens())
{
String n = (String)st.nextToken();
services1[i] = n;
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
}
Can any one please suggest some ideas..
Why not use String.split() ?
You can simply do
String[] my_array = myStr.split("\\s+");
Since '|' is a special character in regular expression, we need to escape it.
for(String token : result.split("\\|"))
{
Toast.makeText(appointment.this, token, Toast.LENGTH_SHORT).show();
}
You can use String.split or Android's TextUtils.split if you need to return [] when the string to split is empty.
From the StringTokenizer API docs:
StringTokenizer is a legacy class that
is retained for compatibility reasons
although its use is discouraged in new
code. It is recommended that anyone
seeking this functionality use the
split method of String or the
java.util.regex package instead.
Since String is a final class, it is by default immutable, which means you cannot make changes to your strings. If you try, a new object will be created, not the same object modified. Therefore if you know in advance that you are going to need to manipulate a String, it is wise to start with a StringBuilder class. There is also StringBuffer for handling threads. Within StringBuilder there are methods like substring():
substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this character sequence.
or getChars():
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.
or delete():
delete(int start, int end)
Removes the characters in a substring of this sequence.
Then if you really need it to be a String in the end, use the String constructor(s)
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder argument.
or
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
Although to understand when to use String methods and when to use StringBuilder, this link or this might help. (StringBuilder comes in handy with saving on memory).