Search code examples
androidswiperefreshlayoutandroid-loadermanager

Android Studio doesn't accept "this" as LoaderCallBack argument inside OnRefreshListener


I am trying to add Swipe Refresh Layout to my fragment. I am using AsyncTaskLoader to load data. While setting the Refresh Layout's OnRefreshListener, I want to restart the loader to load new data (or else should I do different thing) but I can't handle the loaderCallBacks argument. It gives error if I use "this". It says "Found OnRefreshListener, Required LoaderManager.LoaderCallback" object. (I have my OnCreateLoader, OnLoadFinished and OnLoaderReset.)

Here is my code:

// class declaration
public class FragmentTopNews extends Fragment
    implements LoaderManager.LoaderCallbacks<List<NewsItem>>, NewsAdapter.OnItemClickListener{

...

if(activeNetwork != null && activeNetwork.isConnected()){
   LoaderManager loaderManager = getLoaderManager();
   loaderManager.initLoader(NEWS_LOADER_ID, null,this);
   } 

    // SwipeRefreshlayout for refreshing the data
    mSwipeRefreshLayout = rootView.findViewById(R.id.srl_refresher);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mNewsAdapter.clearData();
            mNewsAdapter.notifyDataSetChanged();
            mSwipeRefreshLayout.setRefreshing(true);
            // Here is the problem
            getLoaderManager().restartLoader(NEWS_LOADER_ID, null, this);
        }
    });

My second question is "getloaderManager()" term is strike-through telling me that it is deprecated. What can I do for it?


Solution

  • For your first question:

    When you set the listener, you made a new anonymous inner class instance of the OnRefreshListener, which means this is an instance of it, not your Fragment that's implementing LoaderCallbacks.

    Use FragmentTopNews.this instead:

    getLoaderManager().restartLoader(NEWS_LOADER_ID, null, FragmentTopNews.this);
    

    For your second question:

    android.app.Fragment and its related classes have been deprecated in API 28. You're supposed to use the android.support.v4.app versions instead. In other words, change your imports. You will have to also start using AppCompatActivity and getSupportFragmentManager().

    EDIT:

    Seems the support docs are outdated. I had to actually go to AOSP to find this, but Fragment#getLoaderManager() is indeed deprecated. Use LoaderManager.getInstance(Fragment).