So I am relatively new to Android and I am trying to parse a web based CSV document and use two of the values from this document in my app. I have already successfully parsed a CSV document but it only had 1 row.
The document I am trying to parse looks like this:
Light,2012-08-20T11:04:42.407301Z,107
Temperature,2012-08-20T11:04:42.407301Z,24
I am trying to get the “107” and the “24” values. Can anyone explain how to do this?
This is the code for my current CSV parser class which can successfully parse one line of CSV data.
public class CSVParser {
static InputStream is = null;
private String value;
public String getCSV(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
value = RowData[2];
// do something with "data" and "value"
}
} catch (IOException ex) {
// handle exception
} finally {
try {
is.close();
} catch (IOException e) {
// handle exception
}
}
return value;
}
}
I see you are assigning value = rowData[2], which looks like on the 2 row csv you are only returning the 24 as you assign value each time you read a line. Ie first time it’s assigned 107, then on the next readLine it is overwritten with 24.
You should make the value variable an array (if you know number of items to get) or list that can hold multiple strings. Then you add to this array or list in each readLine loop.
So first time it would be (if using value as a
List<string>)First time round it will add 107 to the list, then next line it will add 24.