繁体   English   中英

对象变空android

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM