Asynctask,首先调用“onPostExecute”并在“doInBackground”之后调用

时间:2013-06-20 09:00:28

标签: android listview android-asynctask

我的代码出了问题。我正在使用asynctask从Web下载JSON对象,并将其插入列表中。

这部分是我在后台下载JSON完成的,然后我将该对象放入OnprogressUpdate()方法的数组中。然后调用onPostExecute()方法来设置适配器。

但这似乎不起作用,因为在onPostExecute()之前调用了doInBackground()。 为什么呢?

这是我的代码:

   public class getListData extends AsyncTask<Void, Song, Long>{

        @Override   
        protected Long doInBackground(Void... params)
        {
            int state =0;
            AsyncHttpClient client = new AsyncHttpClient();

            client.get("http://192.168.1.9:8080/", new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(JSONArray jsonArray) {
                    System.out.println("Successo");

                for (int i = 0; i < jsonArray.length(); i++)
                {
                    JSONObject jsonObject = null;
                try {
                    jsonObject = jsonArray.getJSONObject(i);
                    System.out.println("Leggo il vettore di json");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                        Log.e("canta tu", ""+e);
                        e.printStackTrace();
                }

                String Prezzo = null;

                try {

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                String Titolo = "";
                String ImgUrl="";
                String Genere = null;
                int Difficult = 0;
                String Autore = null;

                try {
                    Titolo =  jsonObject.getString("name"); // per la chiave name,l'informazine sul titolo
                    Autore = jsonObject.getString("artist"); //per l'autore
                    Genere = jsonObject.getString("genre"); //per il genere
                    Difficult = jsonObject.getInt("difficult"); //per la difficoltà
                    ImgUrl = jsonObject.getString("image_url"); //sarà image_url
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                Song t = new Song(Titolo, Autore, Genere, Prezzo, Difficult, ImgUrl);
                System.out.println("inserisco " + Titolo); 
                publishProgress(t);
            }
        }   

        public void onFailure(Throwable e, JSONObject errorResponse){

            System.out.println("error : " + errorResponse);
        }
    });


     return (long) image_details.size(); //the size is 0 because it's called before the onProgressUpdate method

}

        @Override
            protected void onProgressUpdate(Song... values)
            {
                for (Song song : values)
                {
                    image_details.add(song);
                }


            }

        protected void onPostExecute(Long bb) {
            System.out.println("download finished " +bb);
            lv1.setAdapter(new CustomListAdapterLele(getApplicationContext(), image_details));
         }

        }

任何人都可以指出什么是错的。

谢谢

3 个答案:

答案 0 :(得分:3)

我想打电话

HttpClient httpClient = new DefaultHttpClient(); instead of AsyncHttpClient client = new AsyncHttpClient();

应该做的工作。希望它有帮助

答案 1 :(得分:1)

在doInbackground()之前不会调用

onPostExecute(),这不会发生 只需使用此JSON解析器,只传递页面的url以从

获取JSON
jsonobject = JSONParser
            .getJSONfromURL("http://10.0.2.2/myapi/products.php");

然后按照你喜欢的方式解析json对象

public class JSONParser {

    public static JSONObject getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONObject jObj = null;

        // Download JSON data from URL
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }

        // Convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();
                result=sb.toString();
        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }

        try{

            jObj = new JSONObject(result);            
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }

        return jObj;
    }
}

答案 2 :(得分:0)

AsyncTask内有AsyncTask

client.get("http://192.168.1.9:8080/", new JsonHttpResponseHandler()

这是一个asyncCall,它不会等待,程序会在此行之后立即转到onPostExecute()

AsyncTask的错误实施

快速解决方案 可以删除AsyncTask并在UIThreadonSuccess中使用某个处理程序执行UI更新。 / p>