[英]Object become empty android
我有一個帶有 AsyncTask 的類,可以為我收集數據。 我創建了這個類的一個對象,做成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();
}
}
}
}
主要活動
this.catParser = new CategoriesParser(this);
this.catParser.startParse();
mTitle = (String)getTitle(); //and here catParser is empty.
由於任務仍在運行,因此 ArrayList 為空。 在 OnPostExecute 方法中做你需要做的事情,它在 UI 線程中安全地執行,你可以在這里做你需要的一切。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.