Extracting data from Cursor in onLoadFinished for Loader Manager

487 views Asked by At

I have the lines of code in onLoadFinished for my Loader Manager callback in a fragment. The problem with the code is that the favoriteMovies is needed to be displayed in the ArrayAdapter so fo what ever reason, it is zero while the log statement show that the cursor or data is not empty.

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    Log.i(TAG, "Loader Manager Loading Finished: " + data.getCount());
    if (data != null && data.getCount() > 0) {
            while (data.moveToNext()) {
                favouriteMovies.add(
                        new Movie(
                                data.getString(2),
                                data.getString(3),
                                data.getString(4),
                                data.getInt(1),
                                data.getString(5),
                                data.getDouble(6),
                                data.getDouble(7)
                        ));

        }
        setMovies(favouriteMovies);
        hideLoadingProgress();
        mAdapter.notifyDataSetChanged();

    } else {
        showEmptyView(EMPTY_VIEW_TYPE_LOCAL);
        hideLoadingProgress();
    }

}

How can i write this code so that it actually waits fro the while statement to finish before calling the setMovies() method. When i minimize my app to the background and restore it, the movies are diaplayed, but it does not work in the first time it is called.

1

There are 1 answers

0
Jerry Okafor On

After much trial i simple have to check the cursor to know if it is the last index and then call my other function as shown below.

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    Log.i(TAG, "Loader Manager Loading Finished: " + data.getCount());
    favouriteMovies.clear();
    if (data != null && data.getCount() > 0) {
        while (data.moveToNext()) {
            favouriteMovies.add(
                    new Movie(
                            data.getString(2),
                            data.getString(3),
                            data.getString(4),
                            data.getInt(1),
                            data.getString(5),
                            data.getDouble(6),
                            data.getDouble(7)
                    ));
            if (data.isLast()) {
                setMovies(favouriteMovies);
                hideLoadingProgress();
                mAdapter.notifyDataSetChanged();
            }
        }


    } else {
        showEmptyView(EMPTY_VIEW_TYPE_LOCAL);
        hideLoadingProgress();
    }

}