What I want to do is to create a currency converter. I need a live rate for my application. First I will download a csv file from yahoo finance. the csv format is:
"HKDJPY=X",14.1349,"4/21/2016","8:54am" "HKDCNY=X",0.8348,"4/21/2016","8:54am" "HKDTWD=X",4.1611,"4/21/2016","8:53am"
After get this csv file, I would insert it into my sqlite table. But after running the application. I got a exception:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ericyan.travelplaner/com.example.ericyan.travelplaner.CurrencyConverter}: android.os.NetworkOnMainThreadException
How can I fix it?
Here is my code:
public class CurrencyConverter extends BaseActivity {
static InputStream is = null;
String csvURL = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=HKDJPY=X,HKDCNY=X,HKDTWD=X";
private SQLite dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.checklist, contentFrame);
if(checkInternetConnection()) {
getCSV(csvURL);
}
}
public boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return info.isConnected();
} else {
return false;
}
}
public void getCSV(String csvURL) {
try {
URL url = new URL(csvURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
is = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void csvToDB() {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String line;
String from;
String to;
double rate;
String date;
String time;
while((line=reader.readLine())!=null) {
String[] rowData = line.split(" ");
for(String data:rowData) {
String[] city = data.split(",");
from = city[0].substring(1, 3);
to = city[0].substring(4, 6);
rate = Double.parseDouble(city[1]);
date = city[2];
time = city[3];
dbHelper.insertRate(from, to, rate, date, time);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Many Thanks