简体   繁体   中英

AsyncTask onPostExecute not returning the result from doInBackground

I'm trying to load the categories for my app from my Parse database. I can return the result by setting an EditText view to a value of the String ArrayList that i download from the database. But when i return the ArrayList in the doInBackground method, and try to set the same EditText to the result in the onPostExecute method, it says that the index is out of bounds and the ArrayList size is 0. This is my code:

private class DownloadCategories extends AsyncTask<Void, Void, ArrayList<String>> {
    protected ArrayList<String> doInBackground(Void... voi) {
        final ArrayList<String> load = new ArrayList<String>();
        ParseQuery<ParseObject> query = ParseQuery.getQuery("Categories");
        query.findInBackground(new FindCallback<ParseObject>() {
            @SuppressLint("NewApi")
            public void done(List<ParseObject> objects, ParseException e) {
                String category;
                if (e == null) {
                    for (int i = 0; i < objects.size(); i++) {
                        ParseObject pObject = objects.get(i);
                        category = pObject.getString("name");
                        load.add(category);

                    }
                    // onSucced(objects);
                } else {

                }
                //This is where i successfully can set the EditText to the first index.
                address.setText(load.get(0));
            }
        });
        return load;
    }

    protected void onPostExecute(ArrayList<String> loadedCats) {

        //This is where it gives me a null pointer error, since loadedCats is empty.
        address.setText(loadedCats.get(0));

    }

}

Should I just use a class variable an access the variable in the onPostExecute method, or just update the UI from the doInBackground method after i have downloaded the categories, or do you have a solution to the problem with the result?

Thanks in advance.

You don't need the parent AsyncTask , you're already using findInBackground .

What causes the issue here is that you're running the findInBackground in the background, so it's parent AsyncTask will not wait until the done method is called. Instead, it's returning the empty ArrayList. After that the done method is called so it doesn't make any difference to the list.

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