Skip to content

Instantly share code, notes, and snippets.

@barmgeat
Created September 16, 2018 03:47
Show Gist options
  • Save barmgeat/6a974926d01d0bf2a6d87abfd3b11b3d to your computer and use it in GitHub Desktop.
Save barmgeat/6a974926d01d0bf2a6d87abfd3b11b3d to your computer and use it in GitHub Desktop.
setup the CursorLoader SQLite CursorLoader in MainActivity
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int URL_LOADER = 0;
WordCursorAdapter mAdapter;
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
Words._ID,
Words.COLUMN_WORD,
Words.COLUMN_WORD_T,
Words.COLUMN_WORD_T2};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLoaderManager().initLoader(URL_LOADER, null, this);
ListView wordList = findViewById(R.id.wordsListView);
View emptyView = findViewById(R.id.empty_words_layout);
wordList.setEmptyView(emptyView);
mAdapter = new WordCursorAdapter(this, null);
wordList.setAdapter(mAdapter);
}
@Override
public Loader<Cursor> onCreateLoader(int loaderID, @Nullable Bundle bundle) {
/*
* Takes action based on the ID of the Loader that's being created
*/
switch (loaderID) {
case URL_LOADER:
// Returns a new CursorLoader
return new CursorLoader(
MainActivity.this, // Parent activity context
ContractClass.CONTENT_URI, // Table to query
projection, // Projection to return
null, // No selection clause
null, // No selection arguments
null // Default sort order
);
default:
// An invalid id was passed in
return null;
}
}
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor) {
/*
* Moves the query results into the adapter, causing the
* ListView fronting this adapter to re-display
*/
mAdapter.swapCursor(cursor);
}
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader) {
/*
* Clears out the adapter's reference to the Cursor.
* This prevents memory leaks.
*/
mAdapter.changeCursor(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment