0

I tried to load the csv file from server and using the data to draw graph in my Android app.

Here is the code

private class DownloadFilesTask extends AsyncTask<URL, Void, List<String[]>> {
    protected List<String[]> doInBackground(URL... urls) {
        return downloadRemoteTextFileContent();
    }
    protected void onPostExecute(List<String[]> result) {
        if(result != null){
            createLineGraph(result);
        }
    }
}

private void createLineGraph(List<String[]> result){
    DataPoint[] dataPoints = new DataPoint[result.size()];
    for (int i = 0; i < result.size(); i++){
        String[] rows = result.get(i);
        Log.d(TAG, "Output " + Integer.parseInt(rows[0].trim()) + " " + Integer.parseInt(rows[1].trim()));
        dataPoints[i] = new DataPoint(Integer.parseInt(rows[0].trim()), Integer.parseInt(rows[1].trim()));
    }
    LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(dataPoints);
    mGraph.addSeries(series);
}

private List<String[]> downloadRemoteTextFileContent(){
    URL mUrl = null;
    List<String[]> csvLine = new ArrayList<>();
    String[] content = null;
    try {
        mUrl = new URL(PATH_TO_SERVER);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        assert mUrl != null;
        URLConnection connection = mUrl.openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = "";
        while((line = br.readLine()) != null){
            content = line.trim().split(",");
            csvLine.add(content);
        }
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return csvLine;
}

However, the parseInt function in createLineGraph function return me this error

java.lang.NumberFormatException: For input string: "1"

I have no idea why the string read from csv file cannot parse into Integer. Please help!

VPK
  • 3,010
  • 1
  • 28
  • 35
phoon
  • 369
  • 1
  • 6
  • 21
  • Trimming should solve the issue, can you try logging the **raw data** first? `rows[0].trim()` and `rows[1].trim()` – Tenten Ponce Jan 23 '18 at 08:36
  • @TentenPonce since he's already trimming, what's your point? – Stultuske Jan 23 '18 at 08:37
  • 2
    from [this question on code ranch](https://coderanch.com/t/628523/java/java-lang-NumberFormatException-input-string) i would suggest to print the lines' hex values. maybe it is just displayed as 1, but is not really a 1.@VPK he doesn't log the raw data though. he already parses there – XtremeBaumer Jan 23 '18 at 08:40
  • Yes I saw it, but my point is why is it not solving the issue, so I just want to see the log it **raw** because there's something in the **raw data** itself. – Tenten Ponce Jan 23 '18 at 08:40
  • @VPK yes, but not on the same instance as he's trying to parse – Stultuske Jan 23 '18 at 08:41
  • @TentenPonce rows[0].trim() raw data is 1 – phoon Jan 23 '18 at 09:14

0 Answers0