Im working on a Application where im only supposed to display duplicate phone contacts to the user so they can delete the duplicates.
Duplicates
So far im able to display all contacts using the following code:
Main Activity:
private void showContacts() {
Cursor cursor = ContactHelper.getContactCursor(getContentResolver(),"");
String[] fields = new String[]{ContactsContract.Data.DISPLAY_NAME};
adapter =new SimpleCursorAdapter(this,android.R.layout.simple_list_item_multiple_choice,cursor,fields,new int[]{android.R.id.text1});
listView.setAdapter(adapter);
adapter.notifyDataSetChanged(); }
ContactHelper.GetContactsCursor function:
public static Cursor getContactCursor(ContentResolver contactHelper,
String startsWith) {
String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor cur = null;
try {
if (startsWith != null && !startsWith.equals("")) {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " like \"" + startsWith + "%\"", null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
} else {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
}
cur.moveToFirst();
} catch (Exception e) {
e.printStackTrace();
}
return cur;
}
private static long getContactID(ContentResolver contactHelper,
String number) {
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
String[] projection = { ContactsContract.PhoneLookup._ID };
Cursor cursor = null;
try {
cursor = contactHelper.query(contactUri, projection, null, null,
null);
if (cursor.moveToFirst()) {
int personID = cursor.getColumnIndex(ContactsContract.PhoneLookup._ID);
return cursor.getLong(personID);
}
return -1;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
cursor = null;
}
}
return -1; }
how do i filter the unique values from the cursor? and only keep the duplicate contacts according to the phone number if possible?
May be this will work
try {
if (startsWith != null && !startsWith.equals("")) {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " like \"" + startsWith + "%\""
+ " AND "
+ ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " IN (SELECT " + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " as name FROM view_data GROUP BY " +ContactsContract.CommonDataKinds.Phone.NUMBER + " HAVING COUNT(name)>1)",
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
} else {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " IN (SELECT " + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " as name FROM view_data GROUP BY " +ContactsContract.CommonDataKinds.Phone.NUMBER + " HAVING COUNT(name)>1)",
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
}
cur.moveToFirst();
} catch (Exception e) {
e.printStackTrace();
}
Related
I want to be able to read from contacts to my on my Android application but it doesn't seem achievable for APIs below 23. I intend to use this for API 17. How can I achieve this?
This code should work in API5 and above, using the enum ContactsContract.CommonDataKinds you have access to all field.
ContentResolver resolver = context.getContentResolver();
Cursor contacts = null;
try {
contacts = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (contacts.moveToFirst()) {
do {
String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));
Cursor emails = null;
Cursor phones = null;
try {
emails = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = " + contactId, null, null);
while (emails.moveToNext()) {
String email = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
object
}
phones = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String displayName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneContact object
}
} finally {
if (emails != null) {
emails.close();
}
if (phones != null) {
phones.close();
}
}
} while (contacts.moveToNext());
}
} finally {
if (contacts != null) {
contacts.close();
}
}
Try this function. This will give you all the contacts saved in phone
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i(TAG, "Name: " + name);
Log.i(TAG, "Phone Number: " + phoneNo);
}
pCur.close();
}
}
}
if (cur != null) {
cur.close();
}
}
This My Code for Save Contact in external storage directory. But this code is a problem when I open the Contact.txt file on my phone, the last phone number stored on the phone is recorded in the Contact.txt file.
private void getContactList() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
String phoneNo = null;
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("TAG", "Name: " + name);
Log.i("TAG", "Phone Number: " + phoneNo);
}
pCur.close();
File root = new File(Environment.getExternalStorageDirectory(), "cache");
if (!root.exists())
root.mkdirs();
try {
File fileContact = new File(root, "Contact.txt");
FileWriter writer = new FileWriter(fileContact);
writer.append("Name: " + name + " - " + "Phone Number: " + phoneNo);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("TAG", "Game Over.");
}
}
}
if (cur != null) {
cur.close();
}
}
your phones loop here:
while (pCur.moveToNext()) {
phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("TAG", "Name: " + name);
Log.i("TAG", "Phone Number: " + phoneNo);
}
is looping over all the contact's phones, but when the loop exits, phoneNo will contain just the last phone, you need to record all phones into an ArrayList or something like that, and put them all on the file.
Inserting values into table using beans
public static void addGetAssessmentDetail(Context context,
GetAssessmentBean getassessmentDetail) {
DBHelper dbHelper = null;
SQLiteDatabase sqlDBRead = null;
SQLiteDatabase sqlDBWrite = null;
try {
dbHelper = new DBHelper(context, LektzDB.DB_NAME, null,
LektzDB.DB_VERSION);
sqlDBRead = dbHelper.getReadableDatabase();
sqlDBWrite = dbHelper.getWritableDatabase();
ContentValues book = new ContentValues();
book.put(TB_FinalAssessmentValues.CL_1_ID, getassessmentDetail.getId());
book.put(TB_FinalAssessmentValues.CL_2_USER_ID , getassessmentDetail.getUser_id());
book.put(TB_FinalAssessmentValues.CL_3_BOOK_ID, getassessmentDetail.getBook_id());
book.put(TB_FinalAssessmentValues.CL_4_CHAPTER_ID,
getassessmentDetail.getChapter_id());
book.put(TB_FinalAssessmentValues.CL_5_QUESTION_TYPE,
getassessmentDetail.getQuestion_type());
book.put(TB_FinalAssessmentValues.CL_6_QUESTION_ID,
getassessmentDetail.getQuestion_id());
book.put(TB_FinalAssessmentValues.CL_7_OPTION_ID,
getassessmentDetail.getOption_id());
book.put(TB_FinalAssessmentValues.CL_8_MARK,
getassessmentDetail.getMark());
book.put(TB_FinalAssessmentValues.CL_9_NOTES,
getassessmentDetail.getNotes());
book.put(TB_FinalAssessmentValues.CL_10_MATCH_OPTION, getassessmentDetail.getMatchOption());
book.put(TB_FinalAssessmentValues.CL_11_DRAG_VALUES,
getassessmentDetail.getDragValues());
book.put(TB_FinalAssessmentValues.CL_12_ADDED_TIME,
getassessmentDetail.getAdded_time());
Log.i("", "assessment values insertion success" );
} catch (Exception e) {
e.printStackTrace();
}
}
And trying to retrieve those table values into JSON array
public JSONArray getFullAssessmentData(Context mContext, String bookid,
int UserId) {
DBHelper dbh = new DBHelper(mContext, LektzDB.DB_NAME, null,
LektzDB.DB_VERSION);
SQLiteDatabase db = dbh.getReadableDatabase();
JSONArray resultSet = new JSONArray();
try {
Cursor c = db.rawQuery("SELECT * FROM " + TB_FinalAssessmentValues.NAME
+ " WHERE " + TB_FinalAssessmentValues.CL_3_BOOK_ID+ "='"+ bookid + "'", null);
Log.i("tag", "msg vachindi");
if (c.getCount() > 0) {
c.moveToFirst();
do {
c.moveToFirst();
while (c.isAfterLast() == false) {
int totalColumn = c.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (c.getColumnName(i) != null) {
try {
rowObject.put(c.getColumnName(i),
c.getString(i));
} catch (Exception e) {
}
}
}
resultSet.put(rowObject);
c.moveToNext();
}
c.close();
db.close();
}
while (c.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
}
return resultSet;
}
And finally trying to store those values into JSON array
JSONArray fullassessmentjson = rdb.getFullAssessmentData( getContext(), BookId, UserId);
Log.i("Tag123456","Finalcheck"+fullassessmentjson);
DBHelper
db.execSQL("CREATE TABLE IF NOT EXISTS " + TB_FinalAssessmentValues.NAME + "("
+ TB_FinalAssessmentValues.CL_1_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_2_USER_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_3_BOOK_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_4_CHAPTER_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_5_QUESTION_TYPE + " TEXT, "
+ TB_FinalAssessmentValues.CL_6_QUESTION_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_7_OPTION_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_8_MARK + " TEXT, "
+ TB_FinalAssessmentValues.CL_9_NOTES + " TEXT, "
+ TB_FinalAssessmentValues.CL_10_MATCH_OPTION + " TEXT, "
+ TB_FinalAssessmentValues.CL_11_DRAG_VALUES + " TEXT, "
+ TB_FinalAssessmentValues.CL_12_ADDED_TIME + " TEXT)");
and the error is its showing nothing in the Json array
Seems like you're adding the values to your ContentValues object, but do not perform the actual insert into the database.
(because of this you're basically querying an empty table)
You should call the insert() method of SQLiteDatabase at the end of addGetAssessmentDetail() to insert the data into your table:
sqlDBWrite.insert(TABLE_TO_INSERT, null, book);
I search about read song in android and I see a code from you:
private static ArrayList<SongModel> LoadSongsFromCard() {
ArrayList<SongModel> songs = new ArrayList<SongModel>();
// Filter only mp3s, only those marked by the MediaStore to be music and longer than 1 minute
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"
+ " AND " + MediaStore.Audio.Media.MIME_TYPE + "= 'audio/mpeg'"
+ " AND " + MediaStore.Audio.Media.DURATION + " > 60000";
final String[] projection = new String[] {
MediaStore.Audio.Media._ID, //0
MediaStore.Audio.Media.TITLE, //1
MediaStore.Audio.Media.ARTIST, //2
MediaStore.Audio.Media.DATA, //3
MediaStore.Audio.Media.DISPLAY_NAME
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
Cursor cursor = null;
try {
// the uri of the table that we want to query
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; //getContentUriForPath("");
// query the db
cursor = _context.getContentResolver().query(uri,
projection, selection, null, sortOrder);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
//if (cursor.getString(3).contains("AwesomePlaylists")) {
SongModel GSC = new SongModel();
GSC.ID = cursor.getLong(0);
GSC.songTitle = cursor.getString(1);
GSC.songArtist = cursor.getString(2);
GSC.path = cursor.getString(3);
// This code assumes genre is stored in the first letter of the song file name
String genreCodeString = cursor.getString(4).substring(0, 1);
if (!genreCodeString.isEmpty()) {
try {
GSC.genre = Short.parseShort(genreCodeString);
} catch (NumberFormatException ex) {
Random r = new Random();
GSC.genre = (short) r.nextInt(4);
} finally {
songs.add(GSC);
}
}
//}
cursor.moveToNext();
}
}
} catch (Exception ex) {
} finally {
if (cursor != null) {
cursor.close();
}
}
return songs;
}
I'm really learning to program for Android, and modify your code for what I needed , but I have trouble understanding when you assign cursor
cursor = _context.getContentResolver () query ( uri , projection , selection , null, sortOrder ) . ;
Part of _context not understand you kindly explain it please.
If your class extends activity you can use this for _context. If not, you need to pass the context from your activity. The first case mentioned would look like this:
// query the db
cursor = this.getContentResolver().query(uri, projection, selection, null, sortOrder);
__
What is Context in Android?
I'm trying to get all phone numbers of a contact in Android. My code looks like this:
ContentResolver cr = context.getContentResolver();
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER };
String selection = ContactsContract.Data.CONTACT_ID + "=" + contactId;
Cursor nameCur = cr.query(ContactsContract.Data.CONTENT_URI, projection, selection, null, null);
while (nameCur.moveToNext()) {
String contact = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
In principle, it works but the variable "contact" sometimes has values like "null", "1", "4" or "phonenumber#whatsapp". How can I really only get the phone numbers without these stupid WhatsApp Id strings?
You can also check what is contact: phone number or something else:
public static boolean isPhoneNumberValid(CharSequence phone) {
return !(TextUtils.isEmpty(phone)) && Patterns.PHONE.matcher(phone).matches();
}
i use below code and its work, see this:
Cursor cursor = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null,
null, null);
cursor.moveToFirst();
// data = new String[cursor.getCount()][12];
if (cursor.getCount() > 0) {
do {
try {
contactId = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
Uri contactUri = ContentUris.withAppendedId(
Contacts.CONTENT_URI,
Long.parseLong(contactId));
Uri dataUri = Uri.withAppendedPath(contactUri,
Contacts.Data.CONTENT_DIRECTORY);
Cursor phones = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId,
null, null);
if (phones.getCount() > 0) {
ContactClass info = new ContactClass();
info.setid(contactId);
try {
Cursor nameCursor = getContentResolver()
.query(dataUri,
null,
Data.MIMETYPE + "=?",
new String[] { StructuredName.CONTENT_ITEM_TYPE },
null);
nameCursor.moveToFirst();
do {
String firstName = nameCursor
.getString(nameCursor
.getColumnIndex(Data.DATA2));
String lastName = "";
String displayname = cursor
.getString(cursor
.getColumnIndex(Contacts.DISPLAY_NAME_ALTERNATIVE));
if (!firstName.equals(displayname)) {
lastName = nameCursor
.getString(nameCursor
.getColumnIndex(Data.DATA3));
}
if (firstName.equals(null)
&& lastName.equals(null)) {
info.setfirstname("unknown name");
} else if (firstName.equals(null)) {
info.setlastname(lastName);
} else if (lastName.equals(null)) {
info.setfirstname(firstName);
} else {
info.setfirstname(firstName);
info.setlastname(lastName);
}
} while (nameCursor.moveToNext());
nameCursor.close();
} catch (Exception e) {
}
}
phones.close();
}
catch (Exception t) {
}
} while (cursor.moveToNext());
cursor.close();