abcd1234 abcd1234 - 5 months ago 22
Android Question

Android change code to AsyncTask

I have the following code in activity:

ListView lv = (ListView) findViewById(R.id.listViewPizza2);
try {
URL url = new URL("http://api.androidhive.info/pizza/?format=xml");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setDoInput(true);
http.connect();
InputStream in = http.getInputStream();
XmlPullParserPizza2 parser_Pizza = new XmlPullParserPizza2();
pizzaList = parser_Pizza.parse(in);
BinderDataPizza bd_Pizza = new BinderDataPizza(this, pizzaHashmap);
lv.setAdapter(bd_Pizza);
}
catch (Exception e) {
e.printStackTrace();
}


How to do it with
AsyncTask
for
HttpURLConnection
?

Answer

Put the code you want to execute in background in doInBackground. However, you should keep your UI-updating code on the UI thread, so call it in onPostExecute (which is scheduled on the same thread that you call execute() on).

Here's a simple way to convert your code:

final ListView lv = (ListView) findViewById(R.id.listViewPizza2);
new AsyncTask<Void, Void, BinderDataPizza>() {
  @Override
  protected BinderDataPizza doInBackground(Void... params) {
    try {
      URL url = new URL("http://api.androidhive.info/pizza/?format=xml");
      HttpURLConnection http = (HttpURLConnection)url.openConnection();
      http.setDoInput(true);
      http.connect();
      InputStream in = http.getInputStream();
      XmlPullParserPizza2 parser_Pizza = new XmlPullParserPizza2();
      pizzaList = parser_Pizza.parse(in);
      BinderDataPizza bd_Pizza = new BinderDataPizza(this, pizzaHashmap);
      return bd_Pizza;
    } catch (Exception e) {
      Log.e("MyApp", "error while fetching", e);
    }
    return null;
  }
  @Override
  protected void onPostExecute(BinderDataPizza bd_Pizza) {
    if (bd_Pizza != null)
      lv.setAdapter(bd_Pizza);
  }
}.execute();