Reputation: 7
I am having some trouble pulling values from a CSV file for android app that I am working on. The CSV file takes the following format:
Acton Town (District),Acton Town (Piccadilly),2.00
Aldgate (Circle),Aldgate (Metropolitan),4.00
Aldgate East (District),Aldgate East (Hammersmith And City),2.00
I am trying to import it into my java class using the following method:
public ArrayList<Connection> importConnections(){
try
{
//gets the lines.txt file from assets
in = this.getAssets().open("connections.csv");
Scanner scan = new Scanner(in);
TextView lineData = (TextView)findViewById(R.id.displayLine);
String connection = null;
String startingStation = null;
String endingStation = null;
Float duration = 0;
do
{
connection = scan.nextLine();
String delimiter = ",\n";
StringTokenizer tokens = new StringTokenizer(connection, delimiter);
startingStation = tokens.nextToken();
endingStation = tokens.nextToken();
duration = Float.parseFloat(tokens.nextToken());
connections.add(startStation, endStation, duration);
}
while(scan.hasNext());
//for testing purposes
lineData.setText(endingStation);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return connections;
}
If I run this, the app will crash and I can't figure out why. If I set lineData.setText(endingStation)
as lineData.setText(connection)
, it will display the entire row e.g:
Acton Town (District),Acton Town (Piccadilly),2.00
If I comment out the
duration = Float.parseFloat(tokens.nextToken());
it will run the method. Can anyone find any fault with this method?
Upvotes: 0
Views: 298
Reputation: 1629
You could try using OpenCSV http://opencsv.sourceforge.net/
It is pretty simple to use and returns an array of each row.
CSVReader reader = new CSVReader(new FileReader(<filepath>));
String[] temp;
int NUM = #; //number of rows in csv, or insert code to read through file until null.
for(int i = 0; i < NUM; i++)
{
temp = reader.readNext(); //read next line into temp
}
System.out.println(temp[0]); //Acton Town (District)
System.out.println(temp[1]); //Acton Town (Piccadilly)
System.out.println(temp[2]); //2.00 (string)
reader.close();
Like I said, it is easy to use and prevents you from having to parse out the string on your own.
Upvotes: 3