I've builded an AndroidApp which can display all my Contacts. This is how my Cursor looks like:
public Cursor getAllContacts()
{
CursorLoader cl = new CursorLoader(context, ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME);
return cl.loadInBackground();
}
It's working fine, but i want to build a second Cursor, which only can display Favorites I've set in SharedPreferences.
This is where i stuck at:
public Cursor getFavContacts(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Map<String, ?> allEntries = sharedPrefs.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
if(entry.getValue() instanceof Boolean) {
Boolean isFav = (Boolean)entry.getValue();
if(isFav) {
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
String[] split = entry.getKey().split("_");
Log.d("splittedvalue", split[1]);
}
}
}
CursorLoader cl = new CursorLoader(context, ContactsContract.Contacts.CONTENT_URI,null,null,null,ContactsContract.Contacts.DISPLAY_NAME);
Cursor cursor = cl.loadInBackground();
if(cursor != null) {
int count = cursor.getCount();
Log.d("ContactsAdapter", "count: " + count);
}
return cl.loadInBackground();
}
My log is showing correctly only the results i wanted to get. Now i want to tell the CursorLoader to get only my Favorites. How can i do this?
Got a solution!
public Cursor getFavContacts(){
String selection = null ;
String[] split = null;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Map<String, ?> allEntries = sharedPrefs.getAll();
StringBuffer sb = new StringBuffer();
final String COMMATA = ",";
sb.append( ContactsContract.Contacts._ID+" IN (");
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
if(entry.getValue() instanceof Boolean) {
Boolean isFav = (Boolean)entry.getValue();
if(isFav) {
split = entry.getKey().split("_");
sb.append(split[1]);
sb.append(COMMATA);
}
}
}
int sblaenge = sb.length();
sb.delete(sblaenge-1,sblaenge);
sb.append( ")" );
selection = sb.toString();
Log.d(selection, selection);
CursorLoader cl = new CursorLoader(context, ContactsContract.Contacts.CONTENT_URI,null,selection,null,ContactsContract.Contacts.DISPLAY_NAME);
Cursor cursor = cl.loadInBackground();
if(cursor != null) {
int count = cursor.getCount();
Log.d("ContactsAdapter", "count: " + count);
}
return cl.loadInBackground();
}
I create an selection String which contains an sqlite query that gets the relevant contactids.