How to escape comma in a CSV file, android - android

I have a CSV file (the information is with Cyrillic letters, if matters). The CSV class is written so that it reads every row and splits it on a comma:
String[] row = csvLine.split(",");
In the csv I have rows in the following pattern:
ааа,бб, рр, ррр рр тт.
How can I force the CSV be split on the first comma only?
PS: I've already tried using double commas and blackslash in from of the comma, without any success so far.
EDIT:
Here is the whole CSVreader class:
public class CSVReader {
InputStream inputStream;
public CSVReader(InputStream is) {
this.inputStream = is;
}
public List<String[]> read() {
List<String[]> resultList = new ArrayList<String[]>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
} catch(IOException ex) {
throw new RuntimeException("Error in reading CSV file:" + ex);
} finally {
try{
inputStream.close();
} catch(IOException e) {
throw new RuntimeException("Error while closing input stream: " + e);
}
}
return resultList;
}
}
What I need is the above excerpt from the CSV to be split on the first comma only, and the encountered after that to be parsed and shown on the screen.

If you want to split only the first comma of each line, you can use
csvLine.split(",",2);
Where 2 is the limit parameter checking the maximum lenght of the resulting String array. This means that the split will only occur limit-1 times. In your case, 1.
As explained in JavaDocs here.
With input aa,bb,cc,dd you'll get the array {"aa","bb,cc,dd"}

Related

Android: Read a text file from assets from custom line

I'm using this code to read text from assets:
private void Read(String file){
try{
String Name = file;
Name = Name.replaceAll("'", "");
file = getAssets().open(Name + ".txt");
reader = new BufferedReader(new InputStreamReader(file));
line = reader.readLine();
Text ="";
while(line != null){
line = reader.readLine();
if (line !=null){
Text += line+"\n";
LineNumber++;
if(LineNumber==50){btnv.setVisibility(View.VISIBLE);break; }
}
}
if (LineNumber<50){btnv.setVisibility(View.GONE);}
txtv.setText(Text);
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
So I have to read first 50 lines of text, because the text is more then 300 lines, and all I know is to read file line by line, so if I read 300 lines line by line the app freezes for to long, so I read 50 first lines then 50 other lines and so on...
So after I read the first 50 lines with that code I call this other code to read next ones:
private void ContinueReading(){
if (LineNumber >= 50){
try{
while(line != null){
line = reader.readLine();
if (line !=null){
Text += line+"\n";
LineNumber++;
if (LineNumber==100){break;}
if (LineNumber==150){break;}
if (LineNumber==200){break;}
if (LineNumber==250){break;}
if (LineNumber==300){break;}
if (LineNumber==350){break;}
if (LineNumber==400){break;}
if (LineNumber==450){break;}
}
else{
btnv.setVisibility(View.GONE);
}
}
txtv.setText(Text);
}
catch(IOException ioe){ioe.printStackTrace();}
}
}
But as you see I leave open :
file = getAssets().open(emri + ".txt");
reader = new BufferedReader(new InputStreamReader(file));
And this is no good, is anyway to close them and open them again and start reading from last line, or any idea how to start reading from ex. line 50, then from line 100, etc.. ?
This looks like a good place for an AsyncTask. You can even update the TextView with the text as it's being read from the file.
txtv.setText("");
new MyFileReader().execute(filename);
.
.
.
// inner class
public class MyFileReader extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... params) {
try{
InputStream file = getAssets().open(params[0].replaceAll("'", "") + ".txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line;
while ((line = reader.readLine()) != null) {
publishProgress(line + "\n");
}
reader.close();
} catch(IOException ioe){
Log.e(TAG, ioe);
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
txtv.append(values[0]);
}
}
You should use another Thread to read the complete file at once,
Please read this Asynctask in Android
But be care full you can not perform any UI related operations(Like change text of a TextView) on a different Thread instead Of Main Thread....! For that purpose, please also concern below link,
Android “Only the original thread that created a view hierarchy can touch its views.”

Android - Compare String with .txt file in raw folder

I want to know how to compare string value with .txt file's every line and get equal value.
I get All values from .txt file but i don't understand how to compare it.
For example
ABC
CBA
CCC
are in my .txt file,
and in my activity
String someText = "ABC";
and how to compare it with .txt file eacline.
I done below code to get .txt file values.
String result;
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.out);
byte[] b = new byte[in_s.available()];
in_s.read(b);
result = new String(b);
tx.setText(result);
} catch (Exception e) {
// e.printStackTrace();
result = "Error: can't show file.";
tx.setText(result);
}
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("out.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine = reader.readLine();
while (mLine != null) {
//process line
//mLine = reader.readLine();
if ("ABC".equals(mLine)){
Toast.makeText(this, "Yuppppiiiiii", 1000).show();
}
mLine = reader.readLine();
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
I think that your problem is because the way you read the file.
you currently read all file content into a string and this makes you difficult to compare.
Ok, now is the procedures:
You open the file (Create an InputStream, use the Assert, and then wrap it inside a BufferedReader)
You read it line by line, store value in a variable (Use readline() function of bufferreader)
You call the compare string function for this variable and your string (String.equal)
I hope you can understand it clearly. All remain task are about the Android docs.

I keep getting ArrayIndexOutOfBoundsException

Keep getting ArrayIndexOutOfBoundsException when trying to display a specific item form array list data displays fine in logcat but then after displaying throws exception at top please help is the code kind of new to android
public void loadData(){
InputStream file = ourContext.getResources().openRawResource(R.raw.cashpot);
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line ="";
ArrayList<String> values = new ArrayList<String>();
try {
while((line = reader.readLine()) != null) {
values.add(line);
// String[] strings = line.split(",");
/*for(String s : strings) {
values.add(s);
}*/
}
reader.close();
//for(String s : values) Log.d("CSV Test", s);
for(int i = 0; i < values.size();i++){
String[] data = values.get(i).split(",");
Log.d("Test String",data[2] );
}
} catch (IOException e) {
e.printStackTrace();
}
}
Your some lines do not have comma(,)(or 1 comma) and you are trying to split them by comma and storing it in to data array. and you are accessing data[2] location. which might not been created that's why you are getting this exception.
There might not be a 3rd element in your array ,that is created after the split on ",".
You can print value of data before accessing data[2](that might not exist).
Or you can Debug your program and proceed step by step and monitoring the value of each variable.

Android - Comparing String Input On A Textfile Content

May I ask you to guide me how I can accomplish this problem?
I need to compare an inputWord to a string inside a .txt file and if found, return the whole line but if not, show "word not found".
Example:
inputWord: abacus
Text file content:
abaca - n. large herbaceous Asian plant of the banana family.
aback - adv. archaic towards or situated to the rear.
abacus - n. a frame with rows of wires or grooves along which beads are slid, used for calculating.
...
so on
Returns: abacus with its definition
What i am trying to do is compare my inputWord to the words before the " - " (hyphen as delimiter), if they dont match, move to the next line. If they match, copy the whole line.
I hope it doesnt seem like im asking you to "do my homework" but I tried tutorials around different forums and sites. I also read java docs but i really cannot put them together to accomplish this.
Thank you in advance!
UPDATE:
Here's my current code:
if(enhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
String delimiter = " - ";
String del[];
while(s != null)
{
s = in.readLine();
del = s.split(delimiter);
if (enhancedStem.equals(del[0]))
{
in.close();
databaseOutput.setText(s);
break;
}
}
in.close();
}
catch (FileNotFoundException e) {
databaseOutput.setText("" + e);
}
catch (IOException e1) {
databaseOutput.setText("" + e1);
}
}
Thanks a lot! Here's what I came up, and it returns the definition of inputs properly but the problem is, when i enter a word not found in the textfile, the app crashes. The catch phrase doesn't seem to work. Have any idea how I can trap it? Logcat says NullPointerExcepetion at line 4342 which is
s = in.readLine();
Assuming that the format of each line in the text file is uniform. This could be done in the following manner :
1) Read the file line by line.
2) Split each line based on the delimiter and collect the split String tokens in a temp String array.
3) The first entry in the temp token array will be the word before the "-" sign.
4) Compare the first entry in the temp array with the search string and return the entire line if there is a match.
Following code could be put up in a function to accomplish this :
String delimiter = "-";
String[] temp;
String searchString = "abacus";
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.readLine() != null) {
String s = in.readLine();
temp = s.split(delimiter);
if(searchString.equals(temp[0])) {
in.close();
return s;
}
}
in.close();
return ("Word not found");
Hope this helps.
you may try like:
myreader = new BufferedReader(new FileReader(file));
String text = "MyInput Word";
while(!((text.equals(reader.readLine())).equals("0")));

How to parse the CSV file in android application?

I have a CSV file in drawable/asset folder. In the CSV file there are four columns. First one is for date and rest three are for integer data.
I need to parse this CSV file and save the data in separate arrays.
I have searched for a solution, but I don't get proper idea on how to do this.
I like this csv reader: https://mvnrepository.com/artifact/net.sf.opencsv/opencsv/2.3
Just add it to your project.
Example code (assuming there is the file assets/test.csv):
String next[] = {};
List<String[]> list = new ArrayList<String[]>();
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("test.csv")));
while(true) {
next = reader.readNext();
if(next != null) {
list.add(next);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
You can access the imported data with, for example,
list.get(1)[1]
That would return a string.

Categories

Resources