简体   繁体   中英

AsyncTask with result of ArrayList of objects is returning null in OnPostExecute

I'm trying to retrieve some data from API, but i'm always getting null in async task. Here is my asynctask:

private class DownloadTask extends AsyncTask<Bundle, Void, List<Topic>> {

    @Override
    protected void onPreExecute() {
        HomeActivity.mProgressBar.setVisibility(View.VISIBLE);
        HomeActivity.mProgressBar.setIndeterminate(true);
    }

    @Override
    protected List<Topic> doInBackground(Bundle... params) {
        return downloadPhotos(params[0]);
    }

    @Override
    protected void onPostExecute(List<Topic> topics) {
        HomeActivity.mProgressBar.setVisibility(View.INVISIBLE);
        HomeActivity.mProgressBar.setIndeterminate(false);

        Log.d("List Size: ", ""+topics); // 0

        adapter = new TopicListAdapter(activity, topics);
        RecyclerView.LayoutManager manager = new MyCustomLayoutManager(activity);
        recyclerView.setLayoutManager(manager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);
    }
}

Method for retrieving data should merge two arrays into one array because i'm retrieving data from two places:

private List<Topic> downloadPhotos(Bundle params) {
    String profileId = activity.getPreferencesManager().getProfileId();
    List<Topic> topicsFromMe, topicsFromFriends;
    topicsFromFriends = setValuesFromFriends(params);
    topicsFromMe = setValuesFromMe(profileId, params);
    topicsFromFriends.addAll(topicsFromMe);
    sortTopics(topicsFromFriends);
    int k = topicsFromFriends.size();
    Log.d("List Size: ", "" + topicsFromFriends); // here also 0 for size
    if (k > 10)
        topicsFromFriends.subList(10, k).clear();
    return topicsFromFriends;
}

And here is one method where i'm setting values to array list. It is strange that RecyclerView in this case is populated with this array, but i'm not getting results i want. For instance i should sort this list and show only 10 records from it.

private List<Topic> setValuesFromFriends(final Bundle params) {
    final List<Topic> topics = new ArrayList<>();
    activity.getSimpleFacebook().getFriends(new OnFriendsListener() {
        @Override
        public void onComplete(List<Profile> friends) {
            for (final Profile profile : friends) {
                activity.getSimpleFacebook().get(profile.getId(), "photos/uploaded", params,
                        new OnActionListener<List<Photo>>() {
                            @Override
                            public void onComplete(List<Photo> photos) {
                                for (final Photo photo : photos) {
                                    // Initialize instance of Topic
                                    final User user = photo.getFrom();
                                    final Topic topic = new Topic();

                                    topic.setCaption(photo.getName());
                                    topic.setImageId(photo.getId());
                                    topic.setCreatedTime(photo.getCreatedTime());
                                    topic.setPostImage(photo.getSource());
                                    topic.setUserId(user.getId());
                                    topic.setName(user.getName());

                                    final Bundle likeParams = new Bundle();
                                    likeParams.putString("fields", "total_count");
                                    likeParams.putString("limit", "100000");

                                    activity.getSimpleFacebook().get(photo.getId(), "likes",
                                            likeParams, new OnActionListener<List<Like>>() {
                                                @Override
                                                public void onComplete(List<Like> likes) {
                                                    topic.setNumOfLikes(likes.size());
                                                    topics.add(topic);
                                                }

                                                @Override
                                                public void onThinking() {
                                                    super.onThinking();
                                                }
                                            });

                                }
                            }
                        });
            }
        }
    });
    return topics;
}

You are using AsyncTask incorrectly.

AsyncTask is launching another Thread (thread1) where where it is executing the method, doenloadPhotos . This method is calling setValuesFromFriends which is creating another thread (thread2) with the method getFriends . As thread2 has been launched, the rest of the code in setValuesFromFriends will get executed.

So here is how it is working:

private List<Topic> setValuesFromFriends(final Bundle params) {
    final List<Topic> topics = new ArrayList<>();
    //launched process on new thread
    return topics; //this is 0 as topics = new ArrayList<>();
}

So now topicsFromFriends = 0 . Hence you are getting the output = 0.

in effect thread1 is getting executed before thread2 is complete. As the output of thread1 is 0, nothing is displayed in UI after onPostExecute

There is no need of using AsyncTask. You should put all the required code inside the onComplete of the new OnFriendsListener() . This way the info will be shown correctly. You can launch the progressbar before setValuesFromFriends and then remove it in the onComplete .

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