如何将此代码插入AsyncTask

时间:2014-12-04 08:43:38

标签: android json

我有一个listview和json响应的代码,但它抛出错误“NetworkOnMainException”,我认为这个错误是我没有AsynTask执行它的原因,真的吗?但我不知道怎么说呢。感谢

代码是:

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

2 个答案:

答案 0 :(得分:2)

您无法在UI线程上执行网络I / O.从技术上讲,它可以在早期版本的Android(3.0之前),但它是一个非常糟糕的主意,因为它会导致您的应用程序停止响应,并可能导致操作系统因为行为不端而导致您的应用程序被杀。您需要运行后台进程或使用AsyncTask在后台线程上执行网络事务。

尝试这样的代码,

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

    }
}

答案 1 :(得分:0)

developer.android.com为学习目的提供了非常好的文档,因此请在下面学习此链接,以便清楚了解您必须做的事情

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