Android CursorLoader with multiple Contacts._IDs - android

I need to load my cursor with several Contacts using their unique _ID's. I can get a list of all Contacts but I'm having trouble with the SELECTION parameter of the CursorLoader.
What I have so far is :
private static final String SELECTION = Contacts._ID + " IN (?)";
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
Uri contentUri = Contacts.CONTENT_URI;
String selection[] = new String[1];
selection[0] = "8,50";
return new CursorLoader(getActivity(), contentUri, PROJECTION,
SELECTION, selection, null);
}
This return no rows. If I change the selection array to just
selection[0] = "8"
then it correctly returns the contact with an _ID of 8.
Anyone have any ideas on how to retrieve multiple contacts using their _ID's?
Thanks in advance.

You need to use id in (?,?) for selection for 2 items, if you have multiple IDs to select you have to put (?,?,..) as much as your count of selection items. Then give list of IDs in selectionArgs[] array like below:
String[] projection =...
String selectionArgs[] = {"8","50"};
String selection = Contacts._ID + " in (";
for (int i = 0; i < selectionArgs.length; i++) {
selection += "?, ";
}
selection = selection.substring(0, selection.length() - 2) + ")";
return new CursorLoader(getActivity(), contentUri, projection,
selection, selectionArgs, null);

I did a quick test and found this sql statement works for me:
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ) AND ("
+ Contacts._ID + " in (369, 330)))";
Code snippet here:
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
// First, pick the base URI to use depending on whether we are
// currently filtering.
Uri baseUri;
if (mCurFilter != null) {
baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,
Uri.encode(mCurFilter));
} else {
baseUri = Contacts.CONTENT_URI;
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ) AND ("
+ Contacts._ID + " in (369, 330)))";
return new CursorLoader(getActivity(), baseUri,
CONTACTS_SUMMARY_PROJECTION, select, null,
Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
}
For another option you was using, I tested it also. If you do want to use selectParameters, put it in this way:
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ Contacts.DISPLAY_NAME + " != '' ) AND ("
+ Contacts._ID + " in (?,?)))";
String selectionParams[] = new String[2];
selectionParams[0] = "369";
selectionParams[1] = "330";
return new CursorLoader(getActivity(), baseUri,
CONTACTS_SUMMARY_PROJECTION, select, selectionParams,
Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
Hopefully, this will help you.

Related

Android search contacts by phone number and contact name (Both in same time)

I want to query on contacts by phone number and contact name in same time with "LIKE" operator, here is my code :
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1 AND (" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " LIKE '" + query + "%' OR " + ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE '%" + query + "%' OR " + ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE '%" + query + "%' ) ", null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
return cursor;
But my code does not work, it's crashes and android says "data4" and "data1" column does not exist.
Use below code to find contact by name
public String findByName(Context context , String name) {
String result= null;
String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" like'%" + name +"%'";
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor c = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, selection, null, null);
if (c.moveToFirst()) {
result= c.getString(0);
}
c.close();
if(result==null)
result= "This contact is not saved into your device";
return result;
}
Use loader to get fastest results.
public Loader<Cursor> getContactCursor(Context context, Bundle args) {
Uri baseUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String filter = args != null ? args.getString("filter") : null;
if (filter != null && filter.length() > 0) {
return new CursorLoader(context,baseUri, null, "(display_name LIKE ?) OR (data1 LIKE ?)", new String[]{"%" + filter + "%","%" + filter + "%"}, null);
}else{
return new CursorLoader(context,baseUri, projection,null, null, null);
}
}

How to compare a particular field to a string in SQLite

The Cons.getpersonIdForRegisteredUser() method returns a string.
My query has two parts: one is to check the person id and the other is data enabled
#Override
public Loader<Cursor> onCreateLoader(final int i, final Bundle bundle) {
String sortOrder = ContactProviderContract.ContactDatabaseEntry.COLUMN_NAME_FIRST_NAME
+ " COLLATE NOCASE ASC";
String selection = ContactProviderContract.
ContactDatabaseEntry.COLUMN_NAME_PERSON_ID + " != " + Cons.getPersonIdForRegisteredUser(getActivity().getApplicationContext())
+ " AND "
+ ContactProviderContract.ContactDatabaseEntry.COLUMN_NAME_DATA_ENABLED + " = ?";
String[] selectionArgs = { "1" };
return new CursorLoader(getActivity().getApplicationContext(),
ContactProviderContract.CONTACTS_URI,
ContactProviderContract.ContactDatabaseEntry.MIN_DETAILS_COLUMNS,
selection,
selectionArgs,
sortOrder);
}
The error is that the string retrieved from the method Cons.getpersonid...() is considered as a column and not as a string to compare.
If I understand the error correctly, then you should place that Cons.getPersonId... into the selectionArgs.
String selection = ContactProviderContract.
ContactDatabaseEntry.COLUMN_NAME_PERSON_ID + " != ?" +
+ " AND "
+ ContactProviderContract.ContactDatabaseEntry.COLUMN_NAME_DATA_ENABLED + " = ?";
String[] selectionArgs = { "1" , Cons.getPersonIdForRegisteredUser(getActivity().getApplicationContext()) };

Selecting/Joining tables from contacts table but get no ouput - Android

I'm trying to go over all contacts using the contacts, raw_contacts and data tables.
From reading online I believe that Contacts._id is connected with RawContacts.contact_id and Data.raw_contact_id is connected with RowContacts._id. Am I right?
Believing in this I built this method:
public void testingContactsDatabase(String contactId)
{
final String[] projection = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME,
Data.RAW_CONTACT_ID,
Data.MIMETYPE,
StructuredName.DISPLAY_NAME,
StructuredName.FAMILY_NAME,
StructuredName.GIVEN_NAME,
StructuredName.MIDDLE_NAME,
StructuredName.PREFIX, // Common prefixes in English names are "Mr", "Ms", "Dr" etc.
StructuredName.SUFFIX // Common suffixes in English names are "Sr", "Jr", "III" etc.
};
final String selection = Contacts._ID + " = " + contactId + " AND "
+ Contacts._ID + " = " + RawContacts.CONTACT_ID + " AND "
+ Data.RAW_CONTACT_ID + " = " + RawContacts._ID;
final Cursor curStructuredName = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
projection,
selection, null,
//new String[] {contactId, ContactsContract.RawContacts.CONTACT_ID, RawContacts._ID},
null
);
if(curStructuredName.moveToFirst())
{
Log.d("XYZ", "Found something");
}
}
But it never finds anything. I'm not sure if I'm using the correct URI, I've tried with different URIs and either got exceptions or same ouput.
Can someone point me out where I'm doing something wrong?
Thanks
I've solved my problem. Here is my code working now:
// Get the structured name fields
public ArrayList<String> getStructuredName(String contactId)
{
ArrayList<String> structuredList = new ArrayList<String>();
final String[] projection = new String[] {
StructuredName.DISPLAY_NAME,
StructuredName.FAMILY_NAME,
StructuredName.GIVEN_NAME,
StructuredName.MIDDLE_NAME,
StructuredName.PREFIX, // Common prefixes in English names are "Mr", "Ms", "Dr" etc.
StructuredName.SUFFIX // Common suffixes in English names are "Sr", "Jr", "III" etc.
};
final String filter = ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ?";
final String parameters[] = {StructuredName.CONTENT_ITEM_TYPE, contactId};
Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
projection, filter, parameters, null);
if(cursor.moveToFirst())
{
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
final String displayName = cursor.getString(cursor.getColumnIndex(StructuredName.DISPLAY_NAME));
final String familyName = cursor.getString(cursor.getColumnIndex(StructuredName.FAMILY_NAME));
final String givenName = cursor.getString(cursor.getColumnIndex(StructuredName.GIVEN_NAME));
final String middleName = cursor.getString(cursor.getColumnIndex(StructuredName.MIDDLE_NAME));
final String prefix = cursor.getString(cursor.getColumnIndex(StructuredName.PREFIX));
final String suffix = cursor.getString(cursor.getColumnIndex(StructuredName.SUFFIX));
structuredList.add(displayName);
structuredList.add(familyName);
structuredList.add(givenName);
structuredList.add(middleName);
structuredList.add(prefix);
structuredList.add(suffix);
Log.d(tag, "/////////////////////////////////////////////////////");
Log.d(tag, "displayName: " + displayName );
Log.d(tag, "familyName: " + familyName );
Log.d(tag, "givenName: " + givenName );
Log.d(tag, "middleName: " + middleName );
Log.d(tag, "prefix: " + prefix );
Log.d(tag, "suffix: " + suffix );
Log.d(tag, "/////////////////////////////////////////////////////");
}
}
cursor.close();
return structuredList;
}

Android SQLite Query Where and Where

I need to return the ID value from the database where dan == table_column_one and where vrijeme == table_column_two. I don't know how to do this.
public static int returnID(String dan, int vrijeme){
Cursor cursor;
int IDRQ;
cursor = db.query
(
TABLE_NAME,
new String[] { TABLE_COLUMN_ID, TABLE_COLUMN_ONE, TABLE_COLUMN_TWO },
new String[] {TABLE_COLUMN_ONE + " like " + "'%" + dan + "%'", TABLE_COLUMN_TWO + " like " + "'%" + vrijeme + "%'"}, null, null, null, null
);
cursor.moveToFirst();
IDRQ = cursor.getInt(0);
return IDRQ;
} );
This is how I tried, but of course, its wrong.
In SQLiteDatabase.query() the selection comes in two parts. The where clause (a String) and the whereArgs (an array of String).
To add more than one condition to the where clause you can use AND or OR, just like && or || in Java.
A question mark in the where clause is bound to one of the Strings in the whereArgs array.
cursor = db.query(TABLE_NAME, new String[] { TABLE_COLUMN_ID, TABLE_COLUMN_ONE, TABLE_COLUMN_TWO },
TABLE_COLUMN_ONE + " LIKE ? AND " + TABLE_COLUMN_TWO + " LIKE ?",
new String[] {"%" + dan + "%", "%" + vrijeme + "%"},
null, null, null, null);

Selection Statements in Android SQLite

I have a database table with several columns in it. I want to select certain rows by comparing a string entered by a user and select records based on their entry. I have the following code:
SearchbyIngredient.Java
final Button searchbutton1 = (Button) findViewById(R.id.searchbutton1);
searchbutton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Cursor temp = dbIngredientHelper.getDrinks(textView.getText().toString());
String ingred = temp.getString(0);
Context context = getApplicationContext();
iadapter = new IngredientAdapter(temp);
myListView.setAdapter(iadapter);
}
});
}
IngredientHelper.Java
public Cursor getDrinks(String drinkName) throws SQLException{
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME2);
String selection = COLUMN_INGRED1 + "= ' " + drinkName + "'";
String[] asColumnsToReturn = new String[] { COLUMN_ID2, COLUMN_DRINKNAME, COLUMN_INGRED1, COLUMN_AMT1, COLUMN_INGRED2, COLUMN_AMT2, COLUMN_INGRED3, COLUMN_AMT3, COLUMN_INGRED4, COLUMN_AMT4 };
Cursor mCursor2 = queryBuilder.query(dbSqlite, asColumnsToReturn, selection, null, null, null, COLUMN_DRINKNAME);
/*Cursor mCursor = dbSqlite.query(true, TABLE_NAME2, new String[]{
COLUMN_DRINKNAME},
COLUMN_INGRED1 + "= ' " + drinkName + "'", null, null, null, null, null);
if (mCursor != null){
mCursor.moveToFirst();
}*/
mCursor2.moveToFirst();
return mCursor2;
}
My question is regarding
String selection = COLUMN_INGRED1 + "= ' " + drinkName + "'";
This code currently works, however it only finds entries with the user's text in COLUMN_INGRED1 (only a single column in the code). How can I format the statement or make a series of statements so that it also looks for the user's text in COLUMN_INGRED2, COLUMN_INGRED3 and COLUMN_INGRED4? Thank you
Standard SQL applies, use an OR:
COLUMN_INGRED1 + "= ' " + drinkName + "' OR " COLUMN_INGRED2 + "= '" +drinkName + "'" ...;
Note that = will do an exact match, you might want to look into the LIKE operator.

Categories

Resources