我有一个带有AsyncTask的类,可以为我收集数据。我创建了这个类的一个对象,make ArrayList,当它返回另一个类时,这个ArrayList变为空。
这是用于存储和计算数据的类
private Context context;
public ArrayList<Category> categories;
public CategoriesParser(Context context) {
this.context = context;
}
public void startParse(){
this.categories = new ArrayList<Category>();
new JSONParse().execute();
}
private static String url = "http://...";
private static final String TAG_CAT = "categories";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_PARENT = "parent";
JSONArray android = null;
public ArrayList<Category> getCategories(){
return categories;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Подождите пожалуйста ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_CAT);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String parent = c.getString(TAG_PARENT);
categories.add(new Category(id, title, parent)); //data is STILL here
}
pDialog.dismiss();
//even now
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Main_Activity
this.catParser = new CategoriesParser(this);
this.catParser.startParse();
mTitle = (String)getTitle(); //and here catParser is empty.
答案 0 :(得分:0)
当任务仍在运行时,ArrayList为空。在OnPostExecute方法中执行您需要做的事情,它在UI线程中安全地执行,您可以在此处获得所需的一切。