After startQuery, onQueryComplete not be called - android

I used Content Provider to query some information(Android). After I called the startQuery(), I can output the result of my query in Log. But after all the result finished, the function onQueryComplete() was not called. I cannot find the reason.
The code below is my startQuery and onQueryComplete implementations.
public void queryAsync(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, IContinue<Cursor> callback) {
this.startQuery(0, callback, uri, projection, selection, selectionArgs, sortOrder);
}
#Override
public void onQueryComplete(int token, Object cookie, Cursor c) {
Log.e("debug","query complete!");
if (cookie != null) {
#SuppressWarnings("unchecked")
IContinue<Cursor> callback = (IContinue<Cursor>) cookie;
callback.kontinue(c);
}
}
The code below is part of my query code in content provider:
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
switch (uriMatcher.match(uri)){
...
case SINGLE_MESSAGE:
String selection3 = SEQNUM + "=?";
String[] selectArgs2 = { "0" };
Cursor cm = db.query(MESSAGE_TABLE, null, selection3, selectArgs2, null, null, null);
Log.i("debug",Integer.toString(cm.getCount()));
return cm;
}
}
How can I fix this problem?

Related

SQLite selectionArgs not working

I am having some kind of weird problem with my content provider: selectionArgs refused to work for a particular column.
Insertion
void saveFile(File file, Cursor cursor, Context context) {
if (file.isDirectory()) {
throw new IllegalArgumentException(file.getName() + " must be a file");
}
values.put(IS_DIRECTORY, false);
// Some other values.put()
context.getContentResolver().insert(FolderContract.CONTENT_URI, values);
}
And
void saveFolder(File file, String filesNum, Context context, int directTracks) {
if (!file.isDirectory()) {
throw new IllegalArgumentException(file.getName() + " must be a directory");
}
ContentValues values = new ContentValues();
values.put(IS_DIRECTORY, true);
// Some other values.put()
context.getContentResolver().insert(FolderContract.CONTENT_URI, values);
}
My Query
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Timber.w("onCreateLoader: ");
String selection = String.format("%s = ? AND %s = ?", FolderContract.IS_DIRECTORY, FolderContract.PARENT_ID);
String[] selectionArgs = selectionArgs = new String[]{"0", args.getString(FOLDER_PATH)};
return new CursorLoader(getActivity(), FolderContract.CONTENT_URI, null, selection, selectionArgs, null);
}
I want the the query to return the rows with FolderContract.PARENT_ID column = args.getString(FOLDER_PATH) while the FolderContract.IS_DIRECTORY column will be false.
But the above query returns zero results however if I run it without the FolderContract.IS_DIRECTORY in the selection it returns all the matching
results.The weird thing is that if I loop through the cursor, some of the returned rows has its FolderContract.IS_DIRECTORY column as 0 while
others is 1.
ContentProvider
#Override
public Uri insert(#NonNull Uri uri, ContentValues values) {
final SQLiteDatabase database = dbHelper.getWritableDatabase();
long insertedRowId = database.insert(FolderContract.TABLE_NAME, null, values);
if (insertedRowId > -1) {
Uri insertedUri = ContentUris.withAppendedId(CONTENT_URI, insertedRowId);
getContext().getContentResolver().notifyChange(insertedUri, null);
return insertedUri;
}
database.close();
return uri;
}
#Override
public Cursor query(#NonNull Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
final SQLiteDatabase database = dbHelper.getReadableDatabase();
Cursor cursor = database.query(FolderContract.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
Please any idea what I am doing wrong?

SQLite retrieve foreign key values with content provider

I have a sqlite database with "label" and "idea" tables in my Android app. made a foreign key on idea table as idea_label with int values that connected to label_table on its _id.
I use Loader to load my Cursor on the mainActivity that loads my idea table from the provider. As obvious it load idea_label int (But what I seek is to load the value from label_table which sets in label_body).
My loader on mainActivity class
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
DatabaseContract.IdeaEntry._ID,
DatabaseContract.IdeaEntry.COLUMN_IDEA_NAME,
DatabaseContract.IdeaEntry.COLUMN_IDEA_DESCRIPTION,
DatabaseContract.IdeaEntry.COLUMN_IDEA_DATE,
DatabaseContract.IdeaEntry.COLUMN_IDEA_LABEL,
DatabaseContract.IdeaEntry.COLUMN_IDEA_ICON,
DatabaseContract.IdeaEntry.COLUMN_IDEA_IS_ACTIVE,
DatabaseContract.IdeaEntry.COLUMN_IDEA_IS_FAVORITE,
DatabaseContract.IdeaEntry.COLUMN_IDEA_IS_DONE,
DatabaseContract.IdeaEntry.COLUMN_IDEA_IS_ARCHIVED,
DatabaseContract.IdeaEntry.COLUMN_IDEA_ORDER,
};
return new CursorLoader(this,
DatabaseContract.IdeaEntry.CONTENT_URI_IDEA,
projection,
null, // selection
null, // selectionArgs
DatabaseContract.IdeaEntry.COLUMN_IDEA_ORDER // order
);
}
That calls this section on my provider class
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection, #Nullable String selection, #Nullable String[] selectionArgs, #Nullable String sortOrder) {
SQLiteDatabase database = mDatabaseHelper.getReadableDatabase();
Cursor cursor;
int match = sUriMatcher.match(uri);
switch (match){
case IDEAS:
cursor = database.query(DatabaseContract.IdeaEntry.IDEA_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
Is there a way? trigger another loader? or my implementation is wrong in this case? any way or help that direct me to the right direction, will be very appreciated.
With SQLiteQueryBuilder you can join tables in setTables method and then just specify label_body column of label table in projection.
String[] projection = {
DatabaseContract.IdeaEntry._ID,
....
DatabaseContract.LabelEntry.COLUMN_LABEL_BODY,
};
...
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables("IDEA JOIN LABEL ON IDEA.IDEA_LABEL = LABEL._ID");
builder.query(database, projection, selection, selectionArgs, null, null, sortOrder);
Thanks to #gar_r to help and guide me , I did like this with DatabaseContract constants:
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
DatabaseContract.IdeaEntry.IDEA_TABLE_NAME + "." + DatabaseContract.IdeaEntry._ID,
DatabaseContract.IdeaEntry.COLUMN_IDEA_NAME,
DatabaseContract.IdeaEntry.COLUMN_IDEA_DESCRIPTION,
DatabaseContract.IdeaEntry.COLUMN_IDEA_DATE,
DatabaseContract.IdeaEntry.COLUMN_IDEA_LABEL,
DatabaseContract.IdeaEntry.COLUMN_IDEA_ICON,
DatabaseContract.IdeaEntry.COLUMN_IDEA_IS_ACTIVE,
DatabaseContract.IdeaEntry.COLUMN_IDEA_IS_FAVORITE,
DatabaseContract.IdeaEntry.COLUMN_IDEA_IS_DONE,
DatabaseContract.IdeaEntry.COLUMN_IDEA_IS_ARCHIVED,
DatabaseContract.IdeaEntry.COLUMN_IDEA_ORDER,
DatabaseContract.LabelEntry.COLUMN_LABEL_BODY,
};
return new CursorLoader(this,
DatabaseContract.IdeaEntry.CONTENT_URI_IDEA,
projection,
null, // selection
null, // selectionArgs
DatabaseContract.IdeaEntry.COLUMN_IDEA_ORDER // order
);
}
That calls this section on my provider class
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection, #Nullable String selection, #Nullable String[] selectionArgs, #Nullable String sortOrder) {
SQLiteDatabase database = mDatabaseHelper.getReadableDatabase();
Cursor cursor;
int match = sUriMatcher.match(uri);
switch (match){
case IDEAS:
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(DatabaseContract.IdeaEntry.IDEA_TABLE_NAME + " JOIN " + DatabaseContract.LabelEntry.LABEL_TABLE_NAME
+ " ON " + DatabaseContract.IdeaEntry.COLUMN_IDEA_LABEL + " = " + DatabaseContract.LabelEntry.LABEL_TABLE_NAME + "." + DatabaseContract.LabelEntry._ID);
cursor = builder.query(database, projection, selection, selectionArgs, null, null, sortOrder);
break;

Using buildQuery to call query method of database exposed through ContentProvider

I am inserting a ContentProvider layer in between the ORM of SugarORM and the underlying SQLite database in order to be able to use a SyncAdapter with it.
The ORM has a method like this:
public static <T extends SugarRecord<?>> List<T> find(Class<T> type,String whereClause,String[] whereArgs,String groupBy, String orderBy, String limit)
which matches nicely a query method of the SQLiteDatabase:
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
the problem is that the ContentProvider only has one query method which doesn't match the necessary parameters:
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
So I was thinking of turning the parameters from the ORM into a SQL query, and then just passing that to my method, which can then run the raw query and return a cursor, like this:
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
{
switch (uriMatcher.match(uri))
{
case RAW_QUERY:
cursor = db.rawQuery(selection, selectionArgs);//query, arguments
...
the first issue is that this method of SQLiteQueryBuilder is deprecated:
buildQuery (String[] projectionIn, String selection, String[] selectionArgs, String groupBy, String having, String sortOrder, String limit)
so then I tried this:
Object args[] = whereArgs;
String where_query = String.format(whereClause, args);
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(getTableName(type));
String query = builder.buildQuery(null, whereClause, whereArgs, groupBy, null, orderBy, limit);
but the resulting query string is null.
Any suggestions?
public Cursor query(Uri iUri, String[] iProjection, String iSelection,
String[] iSelectionArgs, String iSortOrder) {
SQLiteQueryBuilder mBuilder = new SQLiteQueryBuilder();
mBuilder.setTables(Database.KEY_TABLE);
switch (uriMatcher.match(iUri)) {
case RAW_QUERY:
mBuilder.appendWhere(Database.KEY_ROWID);
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + iUri);
}
Cursor cursor = mBuilder.query(db, iProjection, iSelection,
iSelectionArgs, null, null, iSortOrder);
return cursor;
}
Try this in your code i think this will solve your problem.

Using CursorLoader to get emails causes duplication of emails

I am trying to get email ids of uses contacts. For that I am using Cursor Loader. There is one problem I am getting duplicate email ids also. How to remove email duplicacy. Should I use raw query "SELECT DISTINCT" instead of using CursorLoader or there is some other solution?
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Email.DATA};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP +"='1' AND " + Email.DATA +" IS NOT NULL AND " + Email.DATA +" != \"\" " ;
//showing only visible contacts
String[] selectionArgs = null;
return new CursorLoader(this, ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
}
I recently ran into this problem. It appears that the CursorLoader does not have an implementation of "DISTINCT". My workaround adds a few lines to the onLoadFinish method and extends the BaseAdapter to accept a List parameter:
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String projection[] = {
CommonDataKinds.Phone._ID,
CommonDataKinds.Phone.DISPLAY_NAME,
};
String select = "((" + CommonDataKinds.Phone.DISPLAY_NAME + " NOTNULL) and " + CommonDataKinds.Phone.HAS_PHONE_NUMBER + " > 0)";
String sort = CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
CursorLoader loader = new CursorLoader(
mContext,
CommonDataKinds.Phone.CONTENT_URI,
projection,
select,
null,
sort
);
return loader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
List<String> displayNames = new ArrayList<String>();
cursor.moveToFirst();
while(!cursor.isAfterLast()){
String name = cursor.getString(cursor.getColumnIndex(CommonDataKinds.Phone.DISPLAY_NAME));
if(!displayNames.contains(name))
displayNames.add(name);
cursor.moveToNext();
}
mAdapter.swapCursor(displayNames);
}
Here is my BaseAdapter class:
public class AdapterAddContacts extends BaseAdapter{
private List<String> mData = new ArrayList<String>();
private Context mContext;
public AdapterAddContacts(Context context,List<String> displayNames){
mData = displayNames;
mContext = context;
}
#Override
public int getCount() {
if(mData != null)
return mData.size();
else
return 0;
}
#Override
public Object getItem(int pos) {
return mData.get(pos);
}
#Override
public long getItemId(int id) {
return id;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.entry_add_contacts,parent,false);
String data = mData.get(pos);
TextView textName = (TextView)view.findViewById(R.id.my_contacts_add_display_name);
textName.setText(data);
textName.setTag(data);
return view;
}
public void swapCursor(List<String> displayNames){
mData = displayNames;
this.notifyDataSetChanged();
}
You should be able to modify this specifically for your needs.
Inspired by #mars, I have a solution that does not need a modification of the adapter. The idea is to delete the duplicates of the cursor; as there is no way to do it, we create a new cursor whithout the duplicates.
All the code is in onLoadFinished:
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
MatrixCursor newCursor = new MatrixCursor(PROJECTION); // Same projection used in loader
if (cursor.moveToFirst()) {
String lastName = "";
do {
if (cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)).compareToIgnoreCase(lastName) != 0) {
newCursor.addRow(new Object[]{cursor.getString(0), cursor.getString(1), cursor.getString(2) ...}); // match the original cursor fields
lastName =cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}
} while (cursor.moveToNext());
}
mContactsAdapter.swapCursor(newCursor);
}
I used a small hack in my project - an SQL injection, like that:
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(
this,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] {
"DISTINCT "+ MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME},
null, null, null);
}
This code returns only bundle names and their IDs from Gallery.
So, I'd rewrite your code like that:
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String[] projection = new String[] {
"DISTINCT " + ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP +"='1' AND " + Email.DATA +" IS NOT NULL AND " + Email.DATA +" != \"\" " ;
//showing only visible contacts
String[] selectionArgs = null;
return new CursorLoader(this, ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection, selection, selectionArgs, sortOrder);
}
You can put setDistinct in your content provider.
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
...
final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setDistinct(true);
If you are worried about performance and don't want to play around with cursor again in onLoadFinished(), then there is a small hack
I combined following two solutions from SO.
select distinct value in android sqlite
CursorLoader with rawQuery
And here is my working solution:
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
String tableName;
/*
* Choose the table to query and a sort order based on the code returned
* for the incoming URI.
*/
switch (uriMatcher.match(uri)) {
case NOTIFICATION:
tableName = NOTIFICATIONS_TABLE_NAME;
break;
case NOTIFICATION_TIMESTAMP:
Cursor cursor = db.query(true, NOTIFICATIONS_TABLE_NAME, projection, selection, selectionArgs, TIMESTAMP, null, sortOrder, null);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
case DOWNLOAD:
tableName = DOWNLOADS_TABLE;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (selection != null) {
selection = selection + "=?";
}
Cursor cursor = db.query(tableName, projection, selection, selectionArgs, null, null, sortOrder);
// Tell the cursor what uri to watch, so it knows when its source data
// changes
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
If you see in this case Table name is same is first 2 cases but i created a dummy Uri to achieve this. May not be a very good approach but works perfectly.
I found a solution
Use DISTINCT keyword in selection Array.
String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, "DISTINCT" + ContactsContract.CommonDataKinds.Email.DATA};

Android: SQLite query with selection WHERE clause is not processed

I am trying to limit the database result by defining a SQL WHERE clause in the selection string of the query of the ContentResolver.
Cursor cursor = getContentResolver().query(uri, null, getSelectionString(), null, null);
...
public String getSelectionString() {
// TODO Replace latitude and longitude with database reference.
StringBuilder string = new StringBuilder();
string.append("latitude >= ").append(northEast.getLatitudeE6() / 1e6);
string.append(" AND ");
string.append("latitude <= ").append(southWest.getLatitudeE6() / 1e6);
string.append(" AND ");
string.append("longitude >= ").append(southWest.getLongitudeE6() / 1e6);
string.append(" AND ");
string.append("longitude <= ").append(northEast.getLongitudeE6() / 1e6);
return string.toString();
}
The database columns are defined as follows ...
public class CustomDatabase {
public static final class Contract {
public static final String COLUMN_NAME = "name";
public static final String COLUMN_LATITUDE = "latitude";
public static final String COLUMN_LONGITUDE = "longitude";
}
}
...
I am not particularly sure that I can inspect the query sent in cursor. If so, it does not contain the WHERE clause I sent:
SQLiteQuery: SELECT * FROM custom_db ORDER BY number ASC
Here is an example of the selection string:
latitude >= 48.203927 AND latitude <= 48.213851 AND longitude >= 16.36735 AND longitude <= 16.377648
Questions:
Is the WHERE clause syntactically correct?
Do I need apostrophs?
Am I forced to use both parameters (selection, selectionArgs) at a time in a query?
Where can I debug the whole query?
EDIT:
Here is the query() method of the ContentProvider ...
public class CustomProvider extends ContentProvider {
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
switch (URI_MATCHER.match(uri)) {
case URI_CODE_LOCATIONS:
return mCustomDatabase.getLocations();
}
return null;
}
... obviously, as biegleux guessed, I forgot to pass the parameters. Doh!
Here is the current implementation of the database method ...
public class CustomSQLiteOpenHelper extends SQLiteOpenHelper {
public Cursor getLocation() {
return mDatabaseHelper.getReadableDatabase().query(
CustomSQLiteOpenHelper.TABLE_NAME,
null, null, null, null, null, null);
}
Do you suggest that I change the method signature to the following to pass all parameters? Am I not exposing to much of the database interface this way?
public Cursor getLocations(String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) {
return mDatabaseHelper.getReadableDatabase().query(
CustomSQLiteOpenHelper.TABLE_NAME,
columns, selection, selectionArgs, groupBy, having, orderBy);
}
Ok, so it seems query() method of your provider is causing problems.
Make sure it looks like following.
#Override
public abstract Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
...
// run the query
db.query(db, projection, selection, selectionArgs, groupBy, having, sortOrder, limit);
You are not forced to use selectionArgs parameter, but with it code is more readable.
To debug a query you can use
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
Log.e(TAG, qb.buildQuery(projection, selection, selectionArgs, groupBy, having, sortOrder, limit);
EDIT:
If you have a ContentProvider implemented you don't need to expose getLocations() method as you/users can use ContentProvider's query() method.
You should pass at least those arguments whose can be passed in query() method and those are projection, selection, selectionArgs and sortOrder.
Shouldn't that line be:
Cursor cursor = getContentResolver().query(uri, null, getSelectionString(), null, null);
Note the added parens after getSelectionString to indicate it's a method call, not a string (although I do wonder why that wouldn't throw an error as getSelectionString wouldn't exist as a string if my theory is correct...).

Categories

Resources