简体   繁体   中英

Object become empty android

I have a class with an AsyncTask that collect data for me. I created an object of this class, make ArrayList, and when it comes back to another class, this ArrayList becomes empty.

This is the class for storing and calculating data

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.

The ArrayList is empty as the the task is still running. Do what you need to do in the OnPostExecute method, it's safely executed in the UI thread and you could everything you need here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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