我的代码有问题。我正在使用 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));
}
}
任何人都可以指出什么是错的。
谢谢