I am trying to reverse a Uri's order.
The Uri accesses the phones call logs
Uri allCalls = Uri.parse("content://call_log/calls");
but it stores them from oldest to newest while I want the opposite.
I tried using
Collections.reverse
but that only works for arrays.
Anyone know a solution?
You can input sorting option when you use ContentResover's query function.
query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
Query the given URI, returning a Cursor over the result set.
public static Cursor getAllCallLogs(ContentResolver cr) {
// reading all data in descending order according to DATE
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Uri callUri = Uri.parse("content://call_log/calls");
Cursor curCallLogs = cr.query(callUri, null, null, null, strOrder);
return curCallLogs;
}
Related
I would like to display in the Log.d the current SQL query being generated by a CursorLoader in the onCreateLoader method such as:
return new CursorLoader(
getActivity(), // Parent activity context
WifiEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
WifiEntry.COLUMN_WIFI_NAME + " ASC");
I have looked at the Android docs, and in here, but no success. It is useful to debugging purposes to be able to visualize the SQL string.
Thanks!
UPDATE. I am adding the ContentProvider query method, anybody can answer how to display in the Log the resulting SQL query?
Thanks.
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder)
{
// Get readable database
SQLiteDatabase database = mDbHelper.getReadableDatabase();
// This cursor will hold the result of the query
Cursor cursor;
// Figure out if the URI matcher can match the URI to a specific code
int match = sUriMatcher.match(uri);
switch (match)
{
case WIFIS:
// For the WIFIS code, query the wifi table directly with the given
// projection, selection, selection arguments, and sort order. The cursor
// could contain multiple rows of the pets table.
cursor = database.query(WifiEntry.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
break;
case WIFI_ID:
// For the WIFI_ID code, extract out the ID from the URI.
// the selection will be "_id=?"
selection = WifiEntry._ID + "=?";
selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
cursor = database.query(WifiEntry.TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Cannot query, unknown URI " + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
// Return the cursor
return cursor;
}
I'm not confident with cursors and I'm facing some problem when filtering one with a WHERE clause.
What I'm doing:
ContentResolver contentResolver = context.getContentResolver();
Uri uriConversation = Uri.parse("content://mms-sms/conversations/");
String[] projection = new String[]{"*"};
String selection = "address=" + phoneNumberForThread;
Cursor cursor = contentResolver.query(uriConversation, projection, null, null, null);
Executing this code the cursor get filled and works perfectly.
However, if I swap the null selection argument with my selection String as
Cursor cursor = contentResolver.query(uriConversation, projection, selection, null, null);
I then get an empty cursor. I even check for !phoneNumberForThread.isEmpty()
I think I'm doing something wrong but again I am not confident with cursor yet.
Any help would be really appreciated.
If your input variabel is stored as a string data type, you should enclose it with ' as such:
String selection = "address='" + phoneNumberForThread + "'";
I want to get all the contact starting with the alphabet. Example contact starting with A Is there any way to find that...
Now I am using the code
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
Try following..
managedQuery (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);
Cursor cursor = managedQuery(ContactsContract.Data.CONTENT_URI, null,
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME + " = ?",
new String[] { "A" }, null);
This method was deprecated in API level 11.If it works ok., or otherwise use the below.
CursorLoader (Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);
I'm trying to retrieve a single row from my database using SQLite but for some reason my program crashes. When I search the log I get the next error:
Index -1 is requested with size of 1
I searched the web for solutions but it looks like my code is correct. I can delete a row with that parameter so I know that the position is right. It's probably how I write the query but I just don't know what's wrong with it. Can someone see why I'm doing wrong?
This is the code for the query:
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + /jokes_table");
final Uri _URI = Uri.parse(MyContentProvider.CONTENT_URI + "/2");
String positions = intent.getStringExtra("position_in_db");
Cursor cur = getBaseContext().getContentResolver().query(_URI, new String[] {"Joke","Author","Date","Status"} , MyContentProvider.ID + " = " + intent.getStringExtra("position_in_db") , null , null );
my query method :
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String a;
switch (sUriMatcher.match(uri))
{
case COLLECTION_URI_INDICATOR:
qb.setTables(TABLE_NAME);
qb.setProjectionMap(projectionMap);
break;
case SINGLE_ITEM_URI_INDICATOR:
qb.setTables(TABLE_NAME);
qb.setProjectionMap(projectionMap);
qb.appendWhere(ID);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, null);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
When I try to get all the rows by that query it works fine. The only problem is that I can't retrieve specific row. I try to change the selection with ? and try to see the string before I call the query but it won't work. Trying to reach data from the cursor by
cur.getString(getColumnIndex("Joke"));
ends the program. Can someone help me please?
What is your selection and selectionArgs??
you can try this
selection = ROW_ID_COLUMN_NAME + " =? "; // take a note on the "Space" between this statement
selectionArgs = { ROW_ID };
c = qb.query(db, projection, selection, selectionArgs, null, null, null);
// moveToFirst() method may prevent error when accessing 0 row cursor.
if (c.moveToFirst()) {
c.getString(getColumnIndex("Joke"));
}
What should I do to get my content provider to return the _count column with the count of records? The documentation says it is automatic, but maybe it's only taking about some built-in content provider. Running a query to the database seems not to return it.
If you are using contentProvider then you have to do it like count(*) AS count.
If you use cursor.getCount(), that would not be as efficient as the above approach. With cursor.getCount() you are fetching all the records just to get counts. The entire code should look like following -
Cursor countCursor = getContentResolver().query(CONTENT_URI,
new String[] {"count(*) AS count"},
null,
null,
null);
countCursor.moveToFirst();
int count = countCursor.getInt(0);
The reason why this works is because android needs a column name to be defined.
If you are using ContentProvider.query() a Cursor is returned. Call Cursor.getCount() to get a count of records in the returned cursor.
I had a similiar problem and found this worked for me. In the example below I wanted to get the count of images from the MediaStore provider.
final String[] imageCountProjection = new String[] {
"count(" + MediaStore.Images.ImageColumns._ID + ")",
};
Cursor countCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
imageCountProjection,
null,
null,
null);
countCursor.moveToFirst();
int existingImageCount = countCursor.getInt(0);
With cursor.getCount() you can not assure that it returns the real number of items returned. There are much better ways:
1- If you are using Content Providers, you can do a query and use the Column (_COUNT) included in BaseColumns for your projection
#Override
public Cursor query(SQLiteDatabase db, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
...
projection = new String[] {
ContentContract.NotificationCursor.NotificationColumns._COUNT,
};
...
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, groupBy, having, sortOrder);
return cursor;
}
2- To do a rawQuery using SELECT COUNT(*) as #saurabh says in his response.