Search code examples
javaandroidapicsvyahoo-finance

Get the information from CSV file in Android studio?


My app is trying to get the live currency exchange rate from yahoo finance.

The following is my code, when I click the button, 0.1 is always returned (the value return from the API is always NULL). I have tried my java code, it works, but it is not working on the Android Studio after I paste my code in.

Is that the problem of reading csv file or sth else?

public class MainActivity extends AppCompatActivity {

    public void startConvert(View view){
        EditText amount,from,to;
        amount=(EditText)findViewById(R.id.amount);
        from=(EditText)findViewById(R.id.from);
        to=(EditText)findViewById(R.id.to);
        Double many;
        //many=Double.parseDouble(amount.toString());

        Toast.makeText(this,"haha",Toast.LENGTH_LONG).show();
        Double conv =findExchangeRateAndConvert("EUR", "USD", 1000);

        Toast.makeText(this,Double.toString(conv),Toast.LENGTH_SHORT).show();
    }

    private static Double findExchangeRateAndConvert(String from, String to, int amount) {
        try {
            //Yahoo Finance API

            URL url = new URL("http://quote.yahoo.com/d/quotes.csv?s=" + from + to + "=X&f=l1&e=.csv");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = reader.readLine();
            if (line.length() > 0) {
                return Double.parseDouble(line) * amount;
            }
            reader.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return 0.1;
    }
}

Solution

  • try this one..

            URL url = new URL("http://quote.yahoo.com/d/quotes.csv?s=" + from + to + "=X&f=l1&e=.csv");
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet, localContext);
            String result = "";
            InputStream is = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                     String[] RowData = line.split(",");
                     date = RowData[0];
                     value = RowData[1];
                    // do something with "data" and "value"
                }
            }
            catch (IOException ex) {
                // handle exception
            }
            finally {
                try {
                    is.close();
                }
                catch (IOException e) {
                    // handle exception
                }
            }