shkschneider
shkschneider

Reputation: 18243

Fetching all ParseObject from a ParseQuery before a custom callback

At some point in my Parse-powered application I'm building a ParseQuery to retrieve a certain amount of data from a table ("class" as Parse calls them).

This class includes Pointers to other classes. So data is not available by default (isDataAvailable() == false). I need to fetch() the data on all those Pointers.

Here is my functionning code:

// Simplified code
new ParseQuery<MyClass>("MyClass").where(...).findInBackground(new FindCallback<MyClass>() {
    @Override
    public void done(final List<MyClass> objects, final ParseException pe) {
        for (final Object object : objects) {
            object.fetchIfNeeded();
        }
        myCustomCallback.objects(objects);
    }
});

And here comes my problem: The callbacks in Parse seems to run on UIThread (I tested Looper.getMainLooper().getThread() == Thread.currentThread()).

So I end up with:

I/Choreographer: Skipped X frames! The application may be doing too much work on its main thread.

I know I could use fetchIfNeededInBackground() to avoid that, but then my callback would not run when all the fetches are done.

How to run all fetch actions in background and yet trigger my callback only once they all are done?

Upvotes: 0

Views: 498

Answers (1)

dmestrovic
dmestrovic

Reputation: 722

I had sort of same problems. I needed to do a lot of stuff before triggering callback.

It is really difficult to handle all those requests and know which one came last. So my solution was to create async task myself, and work with synchronous parse methods (delete, fetch, save... those without "inBackground" part =) )

new AsyncTask<Void, Void, Object>() {
        @Override
        protected Object doInBackground(Void... params) {
            List<MyClass> objects = new ParseQuery<MyClass>("MyClass").find();
            for (final Object object : objects) {
                 object.fetchIfNeeded();
            }
            return objects;
        }

        @Override
        protected void onPostExecute(Object objects) {
            myCustomCallback.objects(objects);
        }
    }.execute();

That is general solution for many "nested" calls. Just add them one by one. But for you, I think "include" method on ParseQuery would be enough.

Something like

new ParseQuery<MyClass>("MyClass").where("")
    .include(NAME_OF_THE_OBJECT_IN_PARSE_DB)
    .findInBackground(new FindCallback<MyClass>() {
        @Override
        public void done(final List<MyClass> objects, final ParseException pe) {
            myCustomCallback.objects(objects);
        }
    });

You can check in Parse documentation

I hope this helps.

Upvotes: 1

Related Questions