What would be the correct way to add DISTINCT and/or GROUPBY to ContentResolver-based queries?
Right now I have to create custom URI for each special case.
Is there a better way?
(I still program for 1.5 as lowest common denominator)
You can do nice hack when querying contentResolver, use:
String selection = Models.SOMETHING + "=" + something + ") GROUP BY (" + Models.TYPE;
If you want to use DISTINCT with SELECT more then one column, You need to use GROUP BY.
Mini Hack over ContentResolver.query for use this:
Uri uri = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uri,
new String[]{"DISTINCT address","body"}, //DISTINCT
"address IS NOT NULL) GROUP BY (address", //GROUP BY
null, null);
if(c.moveToFirst()){
do{
Log.v("from", "\""+c.getString(c.getColumnIndex("address"))+"\"");
Log.v("text", "\""+c.getString(c.getColumnIndex("body"))+"\"");
} while(c.moveToNext());
}
This code select one last sms for each of senders from device inbox.
Note: before GROUP BY we always need to write at least one condition.
Result SQL query string inside ContentResolver.query method will:
SELECT DISTINCT address, body FROM sms WHERE (type=1) AND (address IS NOT NULL) GROUP BY (address)
Since no one came to answer I'm just going to tell how I solved this. Basically I would create custom URI for each case and pass the criteria in selection parameter. Then inside ContentProvider#query I would identify the case and construct raw query based on table name and selection parameter.
Here's quick example:
switch (URI_MATCHER.match(uri)) {
case TYPES:
table = TYPES_TABLE;
break;
case TYPES_DISTINCT:
return db.rawQuery("SELECT DISTINCT type FROM types", null);
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
return db.query(table, null, selection, selectionArgs, null, null, null);
In your overridden ContentProvider query method have a specific URI mapping to using distinct.
Then use SQLiteQueryBuilder and call the setDistinct(boolean) method.
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder)
{
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
boolean useDistinct = false;
switch (sUriMatcher.match(uri))
{
case YOUR_URI_DISTINCT:
useDistinct = true;
case YOUR_URI:
qb.setTables(YOUR_TABLE_NAME);
qb.setProjectionMap(sYourProjectionMap);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// If no sort order is specified use the default
String orderBy;
if (TextUtils.isEmpty(sortOrder))
{
orderBy = DEFAULT_SORT_ORDER;
}
else
{
orderBy = sortOrder;
}
// Get the database and run the query
SQLiteDatabase db = mDBHelper.getReadableDatabase();
// THIS IS THE IMPORTANT PART!
qb.setDistinct(useDistinct);
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
if (c != null)
{
// Tell the cursor what uri to watch, so it knows when its source data changes
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
Though I have not used Group By, I have used Distinct in content resolver query.
Cursor cursor = contentResolver
.query(YOUR_URI,
new String[] {"Distinct "+ YOUR_COLUMN_NAME},
null,
null, null);
Adding the Distinct keyword in the projection worked for me too, however, it only worked when the distinct keyword was the first argument:
String[] projection = new String[]{"DISTINCT " + DBConstants.COLUMN_UUID, ... };
In some condition, we can use "distinct(COLUMN_NAME)" as the selection,
and it work perfect.
but in some condition, it will cause a exception.
when it cause a exception, i will use a HashSet to store the column values....
// getting sender list from messages into spinner View
Spinner phoneListView = (Spinner) findViewById(R.id.phone_list);
Uri uri = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uri, new String[]{"Distinct address"}, null, null, null);
List <String> list;
list= new ArrayList<String>();
list.clear();
int msgCount=c.getCount();
if(c.moveToFirst()) {
for(int ii=0; ii < msgCount; ii++) {
list.add(c.getString(c.getColumnIndexOrThrow("address")).toString());
c.moveToNext();
}
}
phoneListView.setAdapter(new ArrayAdapter<String>(BankActivity.this, android.R.layout.simple_dropdown_item_1line, list));
When you have multiple columns in your projection you should do like this:
val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(
"DISTINCT " + MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.BUCKET_ID,
MediaStore.MediaColumns.DATA
)
val groupBySelection = " 1) GROUP BY (${MediaStore.Images.Media.BUCKET_ID}"
contentResolver.query(
uri,
projection,
null,
groupBySelection,
null,
null
)
groupBySelection with closing bracket and number "1" inside is a tiny hack, but it works absolutely fine
I created a utility method for using group by and distinct.
Usage
Here is an example of selecting unseen thread_id with the last message date from the MMS database.
query(contentResolver= contentResolver,
select = arrayOf(Mms.THREAD_ID, "max(${Mms.DATE}) as date"),
from = Mms.CONTENT_URI,
where = "${Mms.SEEN} = 0",
groupBy = "1",
orderBy = "2 desc"
).use {
while (it?.moveToNext() == true){
val threadId = it.getInt(0)
val date = it.getLong(1)
}
}
Source
fun query(
contentResolver: ContentResolver,
from: Uri,
select: Array<String>,
where: String? = null,
groupBy: Array<out String>? = null,
distinct: Boolean = false,
selectionArgs: Array<out String>? = null,
orderBy: String? = null,
): Cursor? {
val tmpSelect = select[0]
val localWhere =
if (groupBy == null) where
else "${where ?: "1"}) group by (${groupBy.joinToString()}"
if (distinct) {
select[0] = "distinct $tmpSelect"
}
val query = contentResolver.query(from, select, localWhere, selectionArgs, orderBy)
select[0] = tmpSelect
return query
}
Maybe its more simple to get distinct values,
try to add the DISTINCT word before the column name you want into the projection table
String[] projection = new String[]{
BaseColumns._ID,
"DISTINCT "+ Mediastore.anything.you.want
};
and use it as an argument to query method of the content resolver!
I hope to help you, cause I have the same question before some days
Related
I am having trouble querying the my SQLiteDatabase using my custom ContentProvider. I am trying to query the database for one user using the 'user_id'. The following pieces of code which are associated with the problem are:
DBProvider.java
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder){
int match_code = myUriMatcher.match(uri);
Cursor c;
switch (match_code){
case USER_BY_ID: {
c = dbHelper.getReadableDatabase().query(
DBContract.User_Table.TABLE_NAME,
projection,
DBContract.User_Table.COLUMN_ID + "='" + ContentUris.parseId(uri) + "'",
selectionArgs,
null,
null,
sortOrder
);
break;
}
default:
throw new UnsupportedOperationException("Not yet implemented");
}
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
ProfileActivity.java
// Columns to load
String[] columns = {
DBContract.User_Table.COLUMN_NAME // String "name"
};
// A cursor is your primary interface to the query results.
Cursor cursor = getActivity().getContentResolver().query(
ContentUris.withAppendedId(DBContract.User_Table.CONTENT_URI, Long.parseLong(id)), // Table to Query
columns, // Columns for the WHERE
DBContract.User_Table.COLUMN_ID, // selection
new String[]{"1"}, // Values for the WHERE
null // Sort Args
);
The error that I am getting is:
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
Any help would be greatly appreciated!
Thanks
You should use:
Cursor cursor = getActivity().getContentResolver().query(
ContentUris.withAppendedId(DBContract.User_Table.CONTENT_URI, Long.parseLong(id)), // Table to Query
columns, // Columns for the WHERE
DBContract.User_Table.COLUMN_ID, // selection
null, // Values for the WHERE
null // Sort Args
);
You are using the selectionArgs parameter wrong. You don't have any ? in the selection parameter and the binding fails. More info in the documentation.
selectionArgs - You may include ?s in selection, which will be
replaced by the values from selectionArgs, in the order that they
appear in the selection. The values will be bound as Strings.
I have set up the cursor but I am still struggling with actually searching it. How do I search for the track name? How do I get its ID so I can pass it to mediaplayer? I have tried different things but didn't succeed.
Basically, I want to know how to search the mediastore for a certain string (string songToPlay in this case), get the results, get the ID of the best match and pass it to my mediaplayer service to play it in the background. The only thing I am asking you is how to get the ID though.
This is the code I am using:
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] songToPlay = value.split("play song");
String[] searchWords = songToPlay[1].split(" ");
String [] keywords = null;
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Media.TITLE + " != ''");
String selection = where.toString();
String[] projection = {
BaseColumns._ID,
MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Artists.ARTIST,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Media.TITLE
};
for (int i = 0; i < searchWords.length; i++) {
keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%';
}
Cursor cursor = this.managedQuery(uri, projection, selection, keywords, MediaStore.Audio.Media.TITLE);
if (cursor.moveToFirst()) {
do{
test.setText(cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)));
}while(cursor.moveToNext());
}
I'm very confused and most of this code is from the internet. I have been trying to do this for 2 days now, that's why I'm asking here. I've done hours of trying by myself.
edit: Current code. How am I supposed to find the location - music ID or whatever I need to play that song from the cursor?
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String songToPlay = value.replaceAll("play song", "").trim();
int music_column_index;
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Artists.ARTIST,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Media.TITLE
};
#SuppressWarnings("deprecation")
Cursor cursor = this.managedQuery(uri,
null,
MediaStore.Audio.Media.TITLE + "=?",
new String[]{songToPlay},
MediaStore.Audio.Media.TITLE + " ASC");
This will search the MediaStore for all songs with title equal to the value of your songToPlay string.
Cursor cursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
MediaStore.Audio.Media.TITLE + "=?",
new String[]{songToPlay},
MediaStore.Audio.Media.TITLE + " ASC");
You can then of course query the cursor to get the ID (and any other column) of any results.
while (cursor.moveToNext()) {
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
// Whatever else you need
}
However this will require an exact match, you may like to use the LIKE operator for a more fuzzy match.
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"));
}
I'm trying to find a contact by display name. The goal is to open this contact and add more data to it (specifically more phone numbers), but I'm struggling to even find the contact I want to update.
This is the code I'm using:
public static String findContact(Context context) {
ContentResolver contentResolver = context.getContentResolver();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI;
String[] projection = new String[] { PhoneLookup._ID };
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ?";
String[] selectionArguments = { "John Johnson" };
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArguments, null);
if (cursor != null) {
while (cursor.moveToNext()) {
return cursor.getString(0);
}
}
return "John Johnson not found";
}
I do have a contact called "John Johnson", but the method always returns "not found". I also tried searching for a contact with just one name, so that makes no difference.
I suspect that it's something wrong with the uri, selection or selection arguments, because I couldn't find any example online of searching for contacts with a given display name, and it seems display name is a special kind of information, different from for example a phone number.
Any ideas how I can achieve to find John Johnson?
UPDATE: I found out how to find a contact by display name:
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Data.CONTENT_URI;
String[] projection = new String[] { PhoneLookup._ID };
String selection = StructuredName.DISPLAY_NAME + " = ?";
String[] selectionArguments = { "John Johnson" };
Cursor cursor = contentResolver.query(uri, projection, selection, selectionArguments, null);
if (cursor != null) {
while (cursor.moveToNext()) {
return cursor.getString(0);
}
}
return "John Johnson not found";
This code returns the contact id of the first contact with display name "John Johnson". In my original code I had the wrong uri and the wrong selection in my query.
I thinks the issue may caused by the projection you set. Projection is used to tell android which column of data you want to query then you only give the id column so the display name won't return. Try to remove the projection to see whether it works.
-- Cursor cursor = contentResolver.query(uri, projection, selection, selectionArguments, null);
++ Cursor cursor = contentResolver.query(uri, null, selection, selectionArguments, null);
Change Your Query URI.
You are using a URI that is meant to filter only phones numbers:
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI;
You need to use a URI that has access to the display_name column, like this:
Uri uri = ContactsContract.Data.CONTENT_URI;
There's a decent breakdown of what URIs to use and when to use them on the Android SDK Documentation:
If you need to read an individual contact, consider using CONTENT_LOOKUP_URI instead of CONTENT_URI.
If you need to look up a contact by the phone number, use PhoneLookup.CONTENT_FILTER_URI, which is optimized for this purpose.
If you need to look up a contact by partial name, e.g. to produce filter-as-you-type suggestions, use the CONTENT_FILTER_URI URI.
If you need to look up a contact by some data element like email address, nickname, etc, use a query against the ContactsContract.Data table. The result will contain contact ID, name etc.
//method for gaining id
//this method get a name and make fetch it's id and then send the id to other method //named "showinformation" and that method print information of that contact
public void id_return(String name) {
String id_name=null;
Uri resultUri = ContactsContract.Contacts.CONTENT_URI;
Cursor cont = getContentResolver().query(resultUri, null, null, null, null);
String whereName = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME + " = ?" ;
String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,name};
Cursor nameCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
id_name = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID));}
nameCur.close();
cont.close();
nameCur.close();
//for calling of following method
showinformation(id_name);
}
//method for showing information like name ,phone, email and other thing you want
public void showinformation(String id) {
String name=null;
String phone=null;
String email=null;
Uri resultUri = ContactsContract.Contacts.CONTENT_URI;
Cursor cont = getContentResolver().query(resultUri, null, null, null, null);
String whereName = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID+ " = ?" ;
String[] whereNameParams1 = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,id};
Cursor nameCur1 = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams1, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur1.moveToNext()) {
name = nameCur1.getString(nameCur1.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));}
nameCur1.close();
cont.close();
nameCur1.close();
String[] whereNameParams2 = new String[] { ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,id};
Cursor nameCur2 = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams2, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur2.moveToNext()) {
phone = nameCur2.getString(nameCur2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));}
nameCur2.close();
cont.close();
nameCur2.close();
String[] whereNameParams3 = new String[] { ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,id};
Cursor nameCur3 = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams3, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur3.moveToNext()) {
email = nameCur3.getString(nameCur3.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));}
nameCur3.close();
cont.close();
nameCur3.close();
String[] whereNameParams4 = new String[] { ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE,id};
Cursor nameCur4 = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams4, ContactsContract.CommonDataKinds.StructuredPostal.DATA);
while (nameCur4.moveToNext()) {
phone = nameCur4.getString(nameCur4.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.DATA));}
nameCur4.close();
cont.close();
nameCur4.close();
//showing result
txadd.setText("Name= "+ name+"\nPhone= "+phone+"\nEmail= "+email);
}
//thank all persons in this site because of many help of me to learn and correction my warn and errors this is only a gift for all of you and ...
The below code should do the trick
if (displayName != null) {
Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, Uri.encode(displayName));
String[] displayNameProjection = { ContactsContract.Contacts._ID, ContactsContract.Contacts.LOOKUP_KEY, Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? ContactsContract.Contacts.DISPLAY_NAME_PRIMARY : ContactsContract.Contacts.DISPLAY_NAME };
Cursor cur = context.getContentResolver().query(lookupUri, displayNameProjection, null, null, null);
try {
if (cur.moveToFirst()) {
return true;
}
} finally {
if (cur != null)
cur.close();
}
return false;
} else {
return false;
}
Reference: Retrieving a List of Contacts Article
I have a big performance issue in my app. After going through traceview i found that most of my app's performance has been consumed by cursors. So i was wondering is there any alternative to Cursors for dealing with device contact list. And if there is no alternative then please advise me how to deal with cursors so it won't slow down your app.
Please HELP!!
Thanks.
This part of my code has performance issue :-
public void getDisplayName()
{
Cursor c1 = this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String personName = null, number = null;
try
{
Log.e(TAG, "I am here!!");
if(c1.getCount() > 0)
{
Log.e(TAG, "I am here2!!");
while(c1.moveToNext())
{
HashMap<String,String> item = new HashMap<String,String>();
String id = c1.getString(c1.getColumnIndex(Contacts._ID));
personName = c1.getString(c1.getColumnIndex(Contacts.DISPLAY_NAME));
item.put("Name", personName);
Cursor cur = this.getContentResolver().query(CommonDataKinds.Phone.CONTENT_URI, null, CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(cur.moveToNext())
{
Log.e(TAG, "I am here!!3");
number = cur.getString(cur.getColumnIndex(CommonDataKinds.Phone.NUMBER));
item.put("Number", number);
}
displayName.add(item);
}
}
}
finally
{
c1.close();
}
}
How to fetch a contact name and number without using Cursors?
That is not possible.
I have a big performance issue in my app.
Rather than using a single query, you use N+1 queries, where N is the number of rows returned by the other query. This is guaranteed to give you poor performance compared to just doing a single query.
You can get the user's name and _ID along with the phone numbers:
String[] PROJECTION=new String[] { Contacts._ID,
Contacts.DISPLAY_NAME,
Phone.NUMBER
};
Cursor c=a.managedQuery(Phone.CONTENT_URI, PROJECTION, null, null, null);
Also, never call getColumnIndex() in a loop, since the value never changes.
I was working on same code and I need email and phone numbers both in first approach It took around 35 seconds to fetch 612 contacts, when I optimized it, it took 2 seconds to fetch 612 contacts
my code.
ContentResolver cr = context.getContentResolver();
String[] projection = new String[] { Contacts.DISPLAY_NAME, Phone.NUMBER };
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = ?";
String[] selectionArgs = { String.valueOf(1) };
Cursor cur = cr.query(Phone.CONTENT_URI, projection, selection, selectionArgs, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phNo = cur.getString(cur.getColumnIndex(Phone.NUMBER));
ContactModel contactModel = new ContactModel();
contactModel.setName(name);
contactModel.setPhoneNumber(phNo);
contactList.add(contactModel);
}
}
String[] projectionEmail = new String[] { Contacts.DISPLAY_NAME, Email.ADDRESS };
String selectionEmail = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = ?";
String[] selectionArgsEmail = { String.valueOf(1) };
Cursor curEmail = cr.query(Email.CONTENT_URI, projectionEmail, selectionEmail, selectionArgsEmail, null);
if (curEmail.getCount() > 0) {
while (curEmail.moveToNext()) {
String Emailname = curEmail.getString(curEmail.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String email = curEmail.getString(curEmail.getColumnIndex(Email.ADDRESS));
ContactModel contactModel = new ContactModel();
contactModel.setName(Emailname);
contactModel.setEmailId(email);
contactList.add(contactModel);
}
}
`