Ryan McClure
Ryan McClure

Reputation: 1223

Android CursorLoader not working in Fragment

I have a FragmentActivity which implements the LoaderManager.LoaderCallbacks interface and I would like to change it to just a Fragment so that I can start it in the background of my splashscreen to grab information from my database. However, when I change FragmentActivity to Fragment I get an error in onCreateLoader:

public class CursorLoaderTest extends Fragment implements
    LoaderManager.LoaderCallbacks<Cursor> {

...
...

@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1)
{
    // Grab URI corresponding with menuItem table
    Uri CONTENT_URI = TabletContentProvider.MENU_ITEM_CONTENT_URI;
    // THIS IS WHERE THE ERROR IS 
    return new CursorLoader(this, CONTENT_URI, null, null, null, null);
}

It wants me to change the CursorLoader object constructor to:

CursorLoader(Context);

And that obviously won't work. I'm working on a project with a team and I'm in charge of the database operations so I'm not super familiar with Fragments / FragmentActivities because I'm not writing code for those parts of the application. Am I missing something obvious here?

Upvotes: 0

Views: 970

Answers (1)

Adam S
Adam S

Reputation: 16394

A CursorLoader has two constructors - the one you're using there, and one which takes simply a Context (which is what your IDE is suggesting as the correct constructor).

The one you're calling requires a Context as the first argument. When in an Activity you can pass this, as an Activity is a Context. A Fragment is not a Context though, so instead of passing this, you'd pass your containing activity:

return new CursorLoader(getActivity(), CONTENT_URI, null, null, null, null);

Upvotes: 5

Related Questions