Txt file to a 2nd array (bidimensional array) - android

I am trying to do a bilinear interpolation and for that I have to read txt file which contains a NxM dimension.
I need to read the value for a specyfic row and column, I think on two options:
Read directly that value from txt file knowing at which column and row attempt. Any idea if its possible?
And the other, read all the file and store on a 2nd array, then read needed value pointing to the exact column and row on 2nd array.
The file separate each value with a doble space. I assume that file have to be stored on assets no? I will thank fot any code or documentation (I do not find out)
Thanks in advance ;)

Your app will definitely run faster if you load the txt file into a 2D array before working with the values. Opening something from persistent storage takes a lot longer than looking it up in memory.
Depending on the size of the array you may run out of memory, that's when you will need to be a bit more clever about which parts of the file you read into memory to work with at each stage.
There are plenty of questions on StackOverflow about reading a 2D array from a text file in Java and it should be similar in Android.

Hi finally I read a bidimensional array as:
public double[][] readArray2D(Context c, String file,int rows,int cols) throws IOException {
double [][] data = new double[rows][cols];
int row = 0;
int col = 0;
BufferedReader bufRdr = null;
try {
bufRdr = new BufferedReader(new InputStreamReader(c.getAssets().open(file)));
} catch (IOException e) {
e.printStackTrace();
}
String line = null;
//read each line of text file
try {
while((line = bufRdr.readLine()) != null && row < data.length)
{
StringTokenizer st = new StringTokenizer(line," ");
while (st.hasMoreTokens())
{
//get next token and store it in the array
data[row][col] = Double.parseDouble(st.nextToken());
col++;
}
col = 0;
row++;
}
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
Thanks for all ;)

Related

String buffer repeats values when used in a loop, Android

I am using a string buffer to read to store values being read from an SQLite database. Inside the loop, the buffer always starts reading from the first database reference.
Eg: The database has the values apple,orange,banana.
Everytime I call the funtion,the string buffer stores the items from the beginning:
first function call: apple
second function call: apple apple orange
third function call: apple apple orange apple orange banana
On the third call i need it just to be: apple orange banana
How can I do this?
public void db{
Cursor res= databaseHelper.getAllData();
if(res!=null){
res.moveToFirst();
try{
while(res.moveToNext())
{
if(res.getString(0)!=null){
stringBuffer.append(res.getString(0)+"\n");
Log.i("TAG",stringBuffer.toString());
stringBuffer1.append(res.getString(1)+"\n");
stringBuffer2.append(res.getString(2)+"\n");
stringBuffer.setLength(0);
stringBuffer1.setLength(0);
stringBuffer2.setLength(0);
}catch(Exception e){}}}
If you need just print "apple orange banana", then use as follow
public void db(){
Cursor res = databaseHelper.getAllData();
if (res != null) {
while (res.moveToNext()) {
String value = res.getString(0) + " ";
stringBuffer.append(value);
Log.d(TAG, stringBuffer.toString())
...
}
res.close()
}
}
Just put StringBuffer stringBuffer = new StringBuffer(""); after public void db{ or clear the stringBuffer by stringBuffer.delete(0, stringBuffer.length()); before you start the loop.
I don't know where you declared stringBuffer but it keeps the previous values. Also you may lose the 1st item in db because you do moveFirst and immediately moveNext, so drop moveFirst
int i =0;
if (cursor.moveToFirst()){
do{
stringBuffer.append.(cursor.getString (i));
i++;
}
while(cursor.moveToNext());
}
cursor.close();
}
Try this instead of that, may this helps you.

Iterate through Java jsonObjects without array included

My problem is that this will create 3 new instances of DailyJobObjects with the same values as object number one (01, Bill, 50). And it's logical that it would do so, so how can I iterate through my jsonObject so I can separate the three objects? I have looked this up tirelessly but everything thing I have seen has and array included in the jsonData which would make things easier but this response Body is coming straight from a database - no arrays, just back to back objects. Iterating only gives me keys which I already did in a separate method to give me one half of my map. Now I need the values. You don't have to give me an answer, you can (I rather) point to something I'm missing. Thanks!
{"id":"01","name":"Bill","salary":"50"},
{"id":"02","name":"James","salary":"60"},
{"id":"03","name":"Ethan","salary":"70"}
JSONObject fields = new JSONObject(jsonData);
mObjectArray = new DailyJobObjectArray[fields.length()];
for(int i=0; i< fields.length(); i++) {
DailyJobObject mObject = new DailyJobObject();
mObject.setName(fields.getString("name"));
mObject.setSalary(fields.getString("salary"));
mObjectArray[i] = mObject;
}
return mObjectArray;
As #Selvin has mentioned, your json is not valid. Either get proper json from the database or parse it in a non-standard way. I would suggest getting a proper json array from the DB.
String[] splitString = jsondata.split("[^a-zA-Z \\{\\}]+(?![^\\{]*\\})");
for ( String s : splitString) {
try {
JSONObject field = new JSONObject(s);
String name = field.getString("name");
String id = field.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
I also agree that your mObject(...) does not make sense at all
Maybe you're looking for something like this
mObject.setName(name)

How to read csv files and set values to TextView using OpenCsv?

I have a csv file with only one column of values. I would like to take the values from each row and display them in separate TextViews using OpenCSV. My code goes something like this:
try {
CSVReader reader = new CSVReader(new FileReader(csvInPath));
String [] row;
while ((row = reader.readNext()) != null) {
tvN[1].setText(row[1].toString());
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It gives me an ArrayIndexOutOfBoundsException error in LogCat and the app force closes.
Can someone tell me what I'm doing wrong and how to do this right? Thanks.
As greenapps pointed out, I was referencing to row[1], which does not exist, as I only have 1 column of values. Turns out OpenCSV reads csv files column by column, and since I had only 1 column, I had to either use row[0], or make my csv have multiple columns. ie:
My csv file:
Name1
Name 2
Name 3
What I should use:
1. Name 2. Name2 3. Name3
It would also be better to rename row[] to column[] to avoid any confusion.

Displaying a unicode character from SQLite database

I have a listView which is populated by data from an SQLite database. One of my fields is a marker with a unicode character of either a full circle: \u25cf or open circle: \u25cb. Both characters display properly when I use a hardcoded string in a text field. However, in my listView I am seeing the text encoding instead of the character.
Does anyone know why this is... and how I get the unicode characters to display?
Thanks.
Update:
The insertion code is
private void loadRecords() throws IOException {
final Resources resources = mContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.records);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, ",");
if (strings.length <2) continue;
long id = addRecord(strings[0].trim(),strings[1].trim(),strings[2].trim(),strings[3].trim(),
strings[4].trim(),strings[5].trim(),strings[6].trim());
}
} finally {
reader.close();
}
}
with the resource being a csv file with one line being e.g.
primaryKey,name,surname,address,phone,email,\u25CB
In your text file, \u25CB are six characters.
To correctly use Unicode characters, put them directly into the file:
primaryKey,name,surname,address,phone,email,●
However, you must ensure that the .csv file has the same encoding as that used by your InputStreamReader (set the second parameter of its constructor).

Reading a textfile database and displaying the results

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.

Categories

Resources