Mamta Kaundal
Mamta Kaundal

Reputation: 453

Fetch data from Back4App(Parse)

I am building an app using Back4App(Parse).

I have two table Post and media. I have to fetch the media(Single or multiple) corresponding to post_id.

So, I am using the following approach: First, I have fetched all posts from Post table and save in ArrayList. Then Using for loop, I fetch particular post_id from ArrayList and send it to media query to find media of that post_id.

But, My problem is that the query is a Asynchronous, because of which the for loop is running ahead of the query and the result of the query is fetched later. for loop is running ahead of query till ArrayList size. How can i rectify this problem.

I am using the following approach:

 for (int i = 0; i < listUserPosts.size(); i++) {
 String postId = listUserPosts.get(i).getPostId();
 ParseQuery<ParseObject> query = ParseQuery.getQuery("Media");
 query.whereEqualTo("post_id", postId);
 query.findInBackground(new FindCallback<ParseObject>() {
                            @Override
                            public void done(List<ParseObject> objects,   ParseException e) {
                       if (objects.size() > 0) {
                       for (int j = 0; j < objects.size(); j++) 
                       {
                       ParseObject parseObject = objects.get(j);
                       //fetching data from parseObject
                       }
                       } 
                       }
                       });

Any help will be deeply appreciated.

Upvotes: 0

Views: 1204

Answers (1)

Davi Mac&#234;do
Davi Mac&#234;do

Reputation: 2984

I didn't understand what exactly you need to do but I suppose your challenge is to know when you have finished fetching all medias. So you'd need something like this:

    for (int i = 0; i < listUserPosts.size(); i++) {
    String postId = listUserPosts.get(i).getPostId();
    ParseQuery<ParseObject> query = ParseQuery.getQuery("Media");
    query.whereEqualTo("post_id", postId);
    query.findInBackground(new FindCallback<ParseObject>() {
        private int currentI = i;

        @Override
        public void done(List<ParseObject> objects,   ParseException e) {
            if (objects.size() > 0) {
                for (int j = 0; j < objects.size(); j++) 
                {
                    ParseObject parseObject = objects.get(j);
                    //fetching data from parseObject
                }
            } 
            if (currentI + 1 == listUserPosts.size()) {
                // It is finished. Do whatever you have to do here.
            }
        }
    });

Upvotes: 1

Related Questions