关于android抛出异常

时间:2016-04-21 09:30:19

标签: android csv

我想要做的是创建货币转换器。我的申请需要实时汇率。首先,我将从雅虎财经下载一个csv文件。 csv格式是:

  

“HKDJPY = X”,14.1349, “2016年4月21日”, “上午8点54分”   “HKDCNY = X”,0.8348 “2016年4月21日”, “8:54”   “HKDTWD = X”,4.1611 “2016年4月21日”, “上午08时53分”

获取此csv文件后,我会将其插入到我的sqlite表中。但是在运行应用程序之后。我有一个例外:

  

java.lang.RuntimeException:无法启动活动   ComponentInfo {com.example.ericyan.travelplaner / com.example.ericyan.travelplaner.CurrencyConverter}:   android.os.NetworkOnMainThreadException

我该如何解决?

这是我的代码:

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();
        }
    }
}
}

非常感谢

0 个答案:

没有答案