0

我的代码有问题。我正在使用 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));
         }

        }

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

谢谢

4

3 回答 3

3

我想打电话

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

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

于 2013-06-20T09:14:52.730 回答
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;
    }
}
于 2013-06-20T09:37:00.550 回答
0

你有一个AsyncTaskAsyncTask

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

这是一个asyncCall,它不会等待,程序会立即运行到onPostExecute()该行之后。

的错误实现AsyncTask

快速解决方案可以只是删除 AsyncTask 并调用它,UIThreadonSuccess使用一些处理程序进行 UI 更新。

于 2013-06-20T09:25:34.237 回答