【问题标题】:Asynctask, first call "onPostExecute" and after "doInBackground"Asynctask,首先调用“onPostExecute”,然后调用“doInBackground”
【发布时间】:2013-06-20 09:00:27
【问题描述】:

我的代码有问题。我正在使用异步任务从网络下载 JSON 对象,并将其插入到列表中。

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

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

这是我的代码:

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

        }

谁能指出哪里错了。

谢谢

【问题讨论】:

  • onPostExecute 不会在 doInbackground() 之前调用。查看文档developer.android.com/reference/android/os/AsyncTask.html 查看 The 4 steps 下的主题
  • 我不确定 AsyncHttpClient 是什么,但从它的名称来看,它异步获取 JSON。因此 doInBackground 方法不会阻塞并以在其他线程中运行的异步请求完成(可能)。使用DefaultHttpClientHttpUrlConnection 你应该很好。
  • @Raghunandan 我知道 onPostExecute 通常在 doInBackGround 之后。问题是它之前运行过。
  • @Akash 感谢您的回答,也许您是对的,但如果我不调用 asyncHttpClient 并使用 defaultHttpClient,我将无法下载和使用 json。 possibile call 2 onPostExecute 是否不同?也许改变参数...
  • @Lele 你又错了。它与您的代码有关。 onPostExecute 在 doInbackground 计算完成后调用

标签: android listview android-asynctask


【解决方案1】:

我想打电话

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

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

【讨论】:

  • 我无法在没有 asyncHttpClient 的情况下使用 json,因为它拥有所有方法。我尝试使用HttpClient httpClient = new DefaultHttpClient(); ((AsyncHttpClient) httpClient).get("http://192.168.1.9:8080", new JsonHttpResponseHandler() { ... 但当然它不起作用,因为有一个类转换异常 06-20 08:10:22.560: E/AndroidRuntime(2851): Caused by: java.lang.ClassCastException: org.apache .http.impl.client.DefaultHttpClient 无法转换为 com.loopj.android.http.AsyncHttpClient
【解决方案2】:

onPostExecute() 不会在 doInbackground() 之前调用,这不会发生 只需使用此 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;
    }
}

【讨论】:

  • 如果我需要下载一个 json 数组而不仅仅是一个 json 对象?
  • 使用函数getJSONArray
【解决方案3】:

AsyncTask 中有一个 AsyncTask

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

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

错误的实现 of AsyncTask

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 2021-02-22
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多