Skip to content

Instantly share code, notes, and snippets.

@AntonioDiaz
Last active December 19, 2020 19:31
Show Gist options
  • Save AntonioDiaz/c48399619719fccfee982774f66a8650 to your computer and use it in GitHub Desktop.
Save AntonioDiaz/c48399619719fccfee982774f66a8650 to your computer and use it in GitHub Desktop.
CursorLoader example in a Fragment
package com.example.android.sunshine.app;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
public static final int LOADER_ID = 0;
private ArrayAdapter<String> forecastAdapter;
private ForecastAdapter mForecastAdapter;
public ForecastFragment() { }
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
getLoaderManager().initLoader(LOADER_ID, null, this);
super.onActivityCreated(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String locationSetting = Utility.getPreferredLocation(getActivity());
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis());
return new CursorLoader(getActivity(), WeatherContract.WeatherEntry.CONTENT_URI, null, null, null, sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mForecastAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mForecastAdapter.swapCursor(null);
}
}
@xht418
Copy link

xht418 commented Nov 23, 2018

”getLoaderManager is deprecated”. Any suggestions? Thank you.

@zarini
Copy link

zarini commented Dec 19, 2020

”getLoaderManager is deprecated”. Any suggestions? Thank you.

LoaderManager.getInstance(LifecycleOwner)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment