Reading a textfile database and displaying the results - android

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.

Related

Create words from random characters using the sqlite database

Let's just say I have the variable String SRand = "KELRSFGLIU", what I want to do is create a word from the SRand variable and search for that word in the database. Or looking for data in a database based on the SRand variable, the words that need to be found do not have to be 10 characters but can be 3, 4 - 10 characters
can this be done?
As an illustration, I want to do something like this:
Ilustration 1:
String SRand = "KELRSFGLIU";
String Suggestion = "";
private void Create_Suggestion(){
//The magic for creating Sugeestion in here
//The result can be "FIRE", "GLUE", "FUR", or something else.
Suggestion = ???;
SearchData(Suggestion);
}
private void SearchData(String Suggest){
//Data Must Be Found
}
Any Idea?
I suggest you use trees in case you want to do that, more info can be found here

Problems adding and retrieving text with newlines in SQLite Android

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);
}

android database delete row by content

Hey Guys ive got a problem with my database.
iam displaying my database in a textview looking like:
hh:mm dd:MM:yyyy text
12:14 12.12.2014 awdawdawd
13:12 13:12:2015 awdaw awdw
onclick iam getting the text by:
StringBuilder ortsplit = new StringBuilder();
String item = ((TextView) view).getText().toString();
String[] itemsplit = item.split("\\s+");
String uhrsplit = itemsplit[0].toString();
String datumsplit = itemsplit[1].toString();
ortsplit.setLength(0);
for (int i = 2; i < itemsplit.length; i++) {
ortsplit.append(" " + itemsplit[i].toString());
}
String sortsplit = String.valueOf(ortsplit);
then iam opening my database:
datasource.open();
datasource.findedel(uhrsplit,datumsplit,sortsplit);
datasource.close();
my datasource.findedel:
public void findedel(String pZeit, String pDatum, String pOrt) {
database.delete("TABELLE", "UHRZEIT="+Zeit +"AND DATUM="+Datum+"AND ORT="+Ort,null);
}
ive got no "id" displayed in the rows, earlier it looked like:
1 hh:mm dd:MM:yyyy text
2 12:14 12.12.2014 awdawdawd
3 13:12 13:12:2015 awdaw awdw
and ive just took the "id" and searched my entries for that id = id and deleted the row, but since i deleted the first row i want to search the row by the content.
any1 got a solution for my problem?
You have multiple errors and also you are prone to SQL injection.
You must use prepared statements or you must add quotes to your strings and escaping the quotes the string has, for example, in your code:
database.delete("TABELLE", "UHRZEIT="+Zeit +"AND DATUM="+Datum+"AND ORT="+Ort,null);
this: DATUM="+Datum+"AND is bad coded, there is not space between Datum and AND so, if datum is equal to test, then you string will be like this: DATUM=testAND. That will return syntax errors in mysql, and also string must be quoted like this: DATUM='test' AND.
The main problem of quoting this way is that if Datum has quotes by itself, you will have errors too. For example, if Datum equals to te'st then your string is going to be like this: DATUM='te'st' AND. As you see, you will have 3 quotes and then will return syntax error.
You must read and understand this before going further, because you will end up with a really messy code plenty of errors and vulnerabilities: http://wangling.me/2009/08/whats-good-about-selectionargs-in-sqlite-queries.html
Good luck ;)
And also, in Java all variable names must start in lowercase (Instead of String Datum use String datum)

Android XML parsing issues using SAX parser

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);
}

Android String Array Manipulation

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).

Categories

Resources