Aitor Ramos Pajares
Aitor Ramos Pajares

Reputation: 361

how insert this code into AsynTask

I have this code with a listview and json response, but it throws the error "NetworkOnMainException", I think this error is why I execute it without AsynTask, reallly? but I don't know how do I have to put it. thanks

the code is:

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      ListView lvCities = (ListView) findViewById(R.id.lv_cities);
      ArrayList<City> citiesAvaiable = new ArrayList<City>();

      try {
        // Llamamos al servicio web para recuperar los datos
        HttpGet httpGet = new HttpGet("http://comupunt.esy.es/cities.php");
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = (HttpResponse)httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        BufferedHttpEntity buffer = new BufferedHttpEntity(entity);
        InputStream iStream = buffer.getContent();

        String aux = "";

        BufferedReader r = new BufferedReader(new InputStreamReader(iStream));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
          aux += line;
        }

        // Parseamos la respuesta obtenida del servidor a un objeto JSON    
        JSONObject jsonObject = new JSONObject(aux);
        JSONArray cities = jsonObject.getJSONArray("cities");

        // Recorremos el array con los elementos cities
        for(int i = 0; i < cities.length(); i++) {
          JSONObject city = cities.getJSONObject(i);

          // Creamos el objeto City
          City c = new City(city.getInt("name"), city.getString("nametwo"));
          c.setData(city.getString("photo"));

          // Almacenamos el objeto en el array que hemos creado anteriormente
          citiesAvaiable.add(c);
        }
      }
      catch(Exception e) {
        e.printStackTrace();
      }

      // Creamos el objeto CityAdapter y lo asignamos al ListView 
      CityAdapter cityAdapter = new CityAdapter(this, citiesAvaiable);
      lvCities.setAdapter(cityAdapter);
    }
    }

Upvotes: 0

Views: 85

Answers (2)

Sam
Sam

Reputation: 4284

You cannot perform network I/O on the UI thread. Technically, it is possible on earlier versions of Android(before 3.0), but it is a really bad idea as it will cause your app to stop responding, and can result in the OS killing your app for being badly behaved. You'll need to run a background process or use AsyncTask to perform your network transaction on a background thread.

try code like this,

public class MainActivity extends Activity {

    ListView lvCities;  
    ArrayList<City> citiesAvaiable = new ArrayList<City>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lvCities = (ListView) findViewById(R.id.lv_cities);
        AsyncExecute asynctask = new asyncExecute();
        asynctask.execute();

    }


    //An asynctask inner class for performing network operation
    class AsyncExecute extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... params) {
             try {
                    // Llamamos al servicio web para recuperar los datos
                    HttpGet httpGet = new HttpGet("http://comupunt.esy.es/cities.php");
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpResponse response = (HttpResponse)httpClient.execute(httpGet);
                    HttpEntity entity = response.getEntity();
                    BufferedHttpEntity buffer = new BufferedHttpEntity(entity);
                    InputStream iStream = buffer.getContent();

                    String aux = "";

                    BufferedReader r = new BufferedReader(new InputStreamReader(iStream));
                    StringBuilder total = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                      aux += line;
                    }

                    // Parseamos la respuesta obtenida del servidor a un objeto JSON    
                    JSONObject jsonObject = new JSONObject(aux);
                    JSONArray cities = jsonObject.getJSONArray("cities");

                    // Recorremos el array con los elementos cities
                    for(int i = 0; i < cities.length(); i++) {
                      JSONObject city = cities.getJSONObject(i);

                      // Creamos el objeto City
                      City c = new City(city.getInt("name"), city.getString("nametwo"));
                      c.setData(city.getString("photo"));

                      // Almacenamos el objeto en el array que hemos creado anteriormente
                      citiesAvaiable.add(c);

                    }
                  }
                  catch(Exception e) {
                    e.printStackTrace();
                  }
            return null;
        }


        @Override
        protected void onPostExecute(Void result) {
            // Creamos el objeto CityAdapter y lo asignamos al ListView 
            CityAdapter cityAdapter = new CityAdapter(MainActivity.this, citiesAvaiable);
             lvCities.setAdapter(cityAdapter);
            super.onPostExecute(result);
        }

    }
}

Upvotes: 1

Aaiam Litigoner
Aaiam Litigoner

Reputation: 98

developer.android.com has provided very good doc for learning purpose so please learn this link below for clear view of what you have to do

http://developer.android.com/reference/android/os/AsyncTask.html

Upvotes: 0

Related Questions