I’m having a problem that i’m sure that it’s really simple to solve but i’m still starting on app developing so i thought you could help me out.
I got an app that has a currency converter in it, and when i push the button to get the conversion it freezes while it’s getting the data from the internet and then comes back to life after some seconds. Here is the code:
public void capturaConversao(String m1, String m2) throws ClientProtocolException, IOException {
BufferedReader resp = null;
endereco = "http://download.finance.yahoo.com/d/quotes.csv?s=" + m1
+ m2 + "=X&f=sl1d1t1ba&e=.csv";
try {
HttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(endereco);
HttpResponse statusCode = client.execute(method);
resp = new BufferedReader(new InputStreamReader(statusCode
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = resp.readLine()) != null) {
sb.append(line);
}
resp.close();
String result = sb.toString();
String[] values = result.split(",");
conversion = values[1];
nextstep++;
} finally {
if (resp != null) {
try {
resp.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Não foi possível se conectar à internet.", Toast.LENGTH_SHORT).show();
}
}
}
}
AsyncTask is the solution for almost all the UI thread woes. 🙂
Here’s a short tutorial.