I want to get the last added contact in the contacts and for getting that i want to pull the max _id of the contact. So here is my query that i want to realise:
AppMain.applicationContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
new String[]{
"MAX(" + ContactsContract.Contacts._ID + ") as max_id",
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER
},
null, null, null);
But unfortunately i am getting this error:
Invalid column MAX(contact_id) as max_id
I tried removing the 'as max_id' but no luck.
Does any one know how to get the last added contact or get the max _id of the contact.
This is not officially supported by Android's ContentProvider framework, especially if the Provider set the strictProjectionMap flag.
But this should work instead, it asks for all contacts sorted by contact-id, and limits the results to 1:
Cursor c = cr.query(Contacts.CONTENT_URI, new String[] { Contacts._ID }, null, null, Contacts._ID + "DESC LIMIT 1");
if (c != null && c.moveToNext()) {
Log.d(TAG, "id is: " + c.getLong(0));
}
Related
** Edit**
This is the URI in question: ContactsContract.Data.CONTENT_URI
Is there any way of knowing if a contact is marked for deletion from this URI?
I already tried querying for the DELETED column, but it crashes with an SQL exception
Thanks for your help
** Attached code **
ContentQuery contentQuery = new ContentQuery(ContactsContract.Data.CONTENT_URI)
.column(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)
.column(ContactsContract.CommonDataKinds.Phone.NUMBER)
.column(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
.column(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY)
.column(CommonDataKinds.Note.NOTE)
.column(Data.MIMETYPE)
.column(ContactsContract.CommonDataKinds.Phone.STARRED)
.where(ContactsContract.CommonDataKinds.Phone.DELETED, "=", "1");
Where ContentQuery is a query builder interface
I haven't tried it, but to get the implicit join of the DELETED field from RawContacts as mentioned in the docs, you need to add RawContacts.DELETED to your projection.
Check the following code, it should print data belonging to deleted contacts:
String[] projection = new String[] { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER, RawContact.DELETED };
Cursor cur = contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, null ,null, null);
while (cur.moveToNext()) {
if (cur.getInt(3) == 1) {
Log.i("TAG", "found a deleted data row: " + cur.getLong(0) + ", " + cur.getString(1) + ", " + cur.getString(2));
}
}
cur.close();
i want to filter multiple data such as
id = "1,3,5" from columnid which is having 1 to 10 id
and another column such as name
name = "a,e,d" from name column of 10 records
and another criteria such as age
age = "21,23,20" from age column of 10 records from same table,
one example i got is
Cursor cursor = db.query("TABLE_NAME",new String[]{"ColumnName"}, "ColumnName=?",new String[]{"value"}, null, null, null);
which is just for one column but i want to get data from multiple column, can anyone help me?
try this working example,
Cursor cursor =
db.query(TABLE_DIARYENTRIES,
new String[] {},
STUDENT_ID + " IN ("+resultStudent+")"+ " AND " +CLASS_NAME + " IN ("+resultClass+")"
+ " AND " +SUBJECT_NAME + " IN ("+resultSubject+")"
null, null, null, null);
and your result string should be 'a','b','c'
I really like the way Google's example is structured. Because for noobies such as myself it makes it really clear what I am doing. And it is also more robust to SQL injections. Here is my modified version of the Google example:
//Column(s) I want returned
String[] projection = {"ColumnIWantReturned"};
//Column(s) I want to filer on
String selection = "FilterColumn1 IN (?) and FilterColumn2 IN (?, ?)";
String[] selectionArgs = {"ArgumentForFilterColumn1", "FirstArgumentForFilterColumn2", "SecondArgumentForFilterColumn2"};
Cursor cursor = db.query(
"MyTable", // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Log.d("this-is-a-test", cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
I am currently working on an Android project in Eclipse and i am having problems with my SQL query.
I am trying to order the query by more than two columns, currently i am doing it by KEY_DAY_ID but i want to also do it by KEY_START_TIME, but i can't get it to work
my query currently looks like this:
Cursor cursor = db.query(TABLE_SESSION, new String[] {KEY_ID, KEY_MODULE_CODE,
KEY_DAY_OF_WEEK, KEY_START_TIME, KEY_DURATION, KEY_SESSION_TYPE, KEY_ROOM},
null, null, null, null, KEY_DAY_ID + " ASC");
Please let me know your thoughts. Thank you in advance!
The last parameter in db.query() method is the order by clause (without the "order by"). All you need to do is separate both columns by a ",". So it would look like:
Cursor cursor = db.query(TABLE_SESSION, new String[] {KEY_ID, KEY_MODULE_CODE,
KEY_DAY_OF_WEEK, KEY_START_TIME, KEY_DURATION, KEY_SESSION_TYPE, KEY_ROOM},
null, null, null, null, KEY_DAY_ID + " ASC, " + KEY_START_TIME + " ASC");
This works for me
SQLiteCursor cursor = (SQLiteCursor) db.query(DbHelper.TIMES, colmn, null, null, null, null, DbHelper.TABLE_DAY + " ASC, " + DbHelper.TABLE_LECTURE_NO + " ASC",null);
Also you can do it in select line like this:
Cursor data = ddbb.rawQuery("SELECT * FROM vacations ORDER BY NAME ,MONTH , date ",null);
in previous code the first probability for the first column "NAME" then will start arrange by the Second probability "MONTH" then the third "date".....
which mean working in series
Or:
Cursor data = ddbb.rawQuery("select * from vacations where NAME = ? ORDER BY MONTH AND date ",new String[]{ns});
in previous code by using "AND" the two conditions are working together in parallel
I'm trying to add Data record to an already exist contact, I find the contact using phone lookup, i take the contact _id field, and add a new data with raw_contact_id set to the _id field.
on some contacts it just doesn't work, it match the data to different contact.
(I think it relates to contacts that are stored on the sim card)
Please advice, maybe you have a different way to add the data
code sample:
LinkedList<Long> lcv = new LinkedList<Long>();
ContentResolver cr = getContentResolver();
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
Cursor c = cr.query(uri, null, null, null, null);
try {
while (c.moveToNext()) {
Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI,
c.getString(c.getColumnIndex(PhoneLookup.LOOKUP_KEY)));
Cursor c2 = getContentResolver().query(lookupUri, new String[] { Contacts._ID, Contacts.DISPLAY_NAME },
null, null, null);
try {
if (c2.moveToNext()) {
Log.i(TAG, "found: " + c2.getLong(c2.getColumnIndex(Contacts._ID)) + ", " + c2.getString(c2.getColumnIndex(Contacts.DISPLAY_NAME)));
lcv.add(c2.getLong(c2.getColumnIndex(Contacts._ID)));
} else {
Log.e(TAG, "failed to lookup");
}
} finally {
c2.close();
}
}
} finally {
c.close();
}
for (Long rawid : lcv) {
Cursor c3 = cr.query(RawContacts.CONTENT_URI, null, RawContacts.CONTACT_ID + "=?", new String[] {rawid+""}, null);
if (c3.moveToNext()) {
Log.e(TAG,"aaaa: " + c3.getString(c3.getColumnIndex(Contacts.DISPLAY_NAME)));
} else {
Log.e(TAG,"errrrror");
}
ContentValues cv = new ContentValues();
cv.put(Data.RAW_CONTACT_ID, rawid + "");
cv.put(Data.MIMETYPE, MyMime.MIMETYPE);
cv.put(Data.DATA1, "mydata");
cv.put(Data.SYNC1, syncvalue);
Uri newIns = cr.insert(ContactsContract.Data.CONTENT_URI, cv);
Log.i(TAG, "insert: " + newIns + ", " + name);
}
The problem lies when you select the Contacts._ID and use this id to populate the data in the LinkedList lcv .
Cursor c2 = getContentResolver().query(lookupUri, new String[] { Contacts._ID, Contacts.DISPLAY_NAME },
null, null, null);
You actually need a RAW_CONTACT_ID here.
The DISPLAY_NAME can be fetched either from Contacts database/ContactsContract.Data' OR 'database/ContactsContract.CommonDataKinds.StructuredName' OR 'database/RawContactsEntity. In the later 2 cases you will be able to fetch the DISPLAY_NAME using RAW_CONTACT_ID
Couple of Key pointers:
Contacts._ID = Data.CONTACT_ID
RawContacts._ID = Data.RAW_CONTACT_ID
RawContacts.CONTACT_ID = Contacts._ID
RawContactsEntity._ID = RawContacts._ID
Sounds confusing?? Let me try...
The Contacts database is divided into 3 tables contacts, raw contacts, and data.
Each table contains column (_ID) which is an auto incremented primary key.
data table contains all the contact info like phone number, mail id, address etc.
The raw contacts points to the actual contact created. Hence we use the raw contacts while adding a contact.
The user cannot add any data in the contacts table. The data in this table is populated internally due to aggregation of contacts.
The reason your logic worked for some of the contacts is: _ID for contacts, raw contacts remains same until there is any contact aggregation taking place. Lets say you add two contacts with same name abc. Here the _ID for raw contacts increments twice while _ID for contacts increments only once as these two contacts gets merged due to the aggregation of contacts
Refer this for more details.
The best approach to fetch the info in your case is by using ContactsContract.RawContactsEntity ( an outer join of the raw_contacts table with the data table)
Reference: http://developer.android.com/reference/android/provider/ContactsContract.RawContactsEntity.html
I would like to get user contacts and then append some kind of regular expression and append them to a list view. I am currently able to get all the contacts via
getContentResolver().query(People.CONTENT_URI, null, null, null, null);
and then pass them to a custom class that extends SimpleCursorAdapter.
So I would like to know how to get only the contacts that match a regular expression and not all of users contacts.
Instead of
getContentResolver().query(People.CONTENT_URI, null, null, null, null);
you should use something like
final ContentResolver resolver = getContentResolver();
final String[] projection = { People._ID, People.NAME, People.NUMBER };
final String sa1 = "%A%"; // contains an "A"
cursor = resolver.query(People.CONTENT_URI, projection, People.NAME + " LIKE ?",
new String[] { sa1 }, null);
this uses a parameterized request (using ?) and provides the actual values as a different argument, this avoids concatenation and prevents SQL injection mainly if you are requesting the filter from the user. For example if you are using
cursor = resolver.query(People.CONTENT_URI, projection,
People.NAME + " = '" + name + "'",
new String[] { sa1 }, null);
imagine if
name = "Donald Duck' OR name = 'Mickey Mouse") // notice the " and '
and you are concatenating the strings.
You can query the content provider with sql type input, the Query method is just a wrapper for an sql command.
Here is an example where I query for a Contacts name given a particular number
String [] requestedColumns = {
Contacts.Phones.NAME,
Contacts.Phones.TYPE
};
Cursor contacts = context.getContentResolver().query(
Contacts.Phones.CONTENT_URI,
requestedColumns,
Contacts.Phones.NUMBER + "='" + phoneNumber + "'",
null, null);
Note that instead of null I have parameters that build up the sql statement.
The requestColumns are the data I want to get back and Contacts.Phones.NUMBER + "='" + phoneNumber + "'" is the Where clause, so I retrieve the Name and Type where the Phone Number matches
You should be able to put a legal SQLite WHERE clause as the third argument to the query() method, including a LIKE, but there's no native REGEXP function in SQLite and Android doesn't seem to let you define your own. So depending how complex your needs are, a set of other SQLite conditions and LIKE expressions might do the trick.
See the documentation on the query method under ContentResolver and SQLite expressions.
Actually REGEXP with Calllog Content Provider works (means that regexp() function is defined for that content provider's Database https://sqlite.org/lang_expr.html#regexp)! But it is very slow: ~15 sec across ~1750 records.
String regexp = "([\\s\\S]{0,}" +
TextUtils.join("||[\\s\\S]{0,}", numbers) +
")";
cursor = context.getContentResolver().query(
CallLog.Calls.CONTENT_URI,
null,
CallLog.Calls.NUMBER + " REGEXP ?",
new String[]{regexp},
CallLog.Calls.DATE + " DESC"
);