【发布时间】: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 方法不会阻塞并以在其他线程中运行的异步请求完成(可能)。使用
DefaultHttpClient或HttpUrlConnection你应该很好。 -
@Raghunandan 我知道 onPostExecute 通常在 doInBackGround 之后。问题是它之前运行过。
-
@Akash 感谢您的回答,也许您是对的,但如果我不调用 asyncHttpClient 并使用 defaultHttpClient,我将无法下载和使用 json。 possibile call 2 onPostExecute 是否不同?也许改变参数...
-
@Lele 你又错了。它与您的代码有关。 onPostExecute 在 doInbackground 计算完成后调用
标签: android listview android-asynctask