Created
May 30, 2016 09:48
-
-
Save GlennReilly/2b5e53caeaa1937a77f8cd7cca0ff0f5 to your computer and use it in GitHub Desktop.
Using-rawquery-in-contentprovider
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
I am using my custom ContentProvider to communicate with sqlite database. I would like to display on a list (using ListFragment), data that comes from two tables (with many to many relation). The only solution I can think of for such case is to use rawQuery. And the questions is, if it is a good practice, or should I solve this in some other way? | |
Example of tables: | |
Table A: ID, COLUMN_FROM_A | |
Table B: ID, COLUMN_FROM_B | |
Joining table AB: ID, FK_ID_A, FK_ID_B | |
Example of overridden query method in ContentProvider: | |
@Override | |
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { | |
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); | |
Cursor cursor = null; | |
int uriType = URIMatcher.match(uri); | |
switch (uriType) { | |
case TABLE_A_URI: | |
queryBuilder.setTables("TABLE_A"); | |
cursor = queryBuilder.query(databaseHelper.getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder); | |
break; | |
case TABLE_B_URI: | |
queryBuilder.setTables("TABLE_B"); | |
cursor = queryBuilder.query(databaseHelper.getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder); | |
break; | |
case TABLE_JOIN_A_B_URI: | |
cursor = databaseHelper.getReadableDatabase().rawQuery("select a.COLUMN_FORM_A, b.COLUMN_FROM_B from TABLE_A a, TABLE_B b, TABLE_AB ab where ab.FK_ID_A=a.ID and ab.FK_ID_B=b.ID", null); | |
break; | |
default: | |
throw new IllegalArgumentException("Unknown URI"); | |
} | |
cursor.setNotificationUri(getContext().getContentResolver(), uri); | |
return cursor; | |
//from http://stackoverflow.com/questions/11578857/is-it-a-good-practice-to-use-rawquery-in-contentprovider |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment