-
-
Save jesselima/751a33c38d7cf49b1387e49b4fbaf1d0 to your computer and use it in GitHub Desktop.
CursorLoader example in a Fragment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment