Created
September 16, 2018 03:47
-
-
Save barmgeat/6a974926d01d0bf2a6d87abfd3b11b3d to your computer and use it in GitHub Desktop.
setup the CursorLoader SQLite CursorLoader in MainActivity
This file contains hidden or 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
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