24 Stimmen

Wie erhalte ich den Vor- und Nachnamen von Android-Kontakten?

Wie erhalte ich die folgenden Felder von Android-Kontakten? Ich benutze Android 2.2.

  1. Namenspräfix
  2. Vornamen
  3. Mittlerer Name
  4. Nachname
  5. Namenspräfix
  6. Phonetischer Vorname
  7. Phonetischer zweiter Vorname
  8. Phonetischer Familienname

1voto

Harry Moreno Punkte 8993

Experimentieren mit dem ContactsContract.Data.CONTENT_URI Ende 2015 auf Marshmallow. Ich bin nicht in der Lage, die GIVEN_NAME oder ähnlichen Bereichen. Ich glaube, die neueren Apis haben diese veraltet. Führen Sie den folgenden Code aus, um die Spalten auf Ihrem Telefon auszudrucken

Uri uri = ContactsContract.Data.CONTENT_URI;
String selection = ContactsContract.Data.MIMETYPE + " = ?";
String[] selectionArgs = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
Cursor cursor = contentResolver.query(
            uri,       // URI representing the table/resource to be queried
            null,      // projection - the list of columns to return.  Null means "all"
            selection, // selection - Which rows to return (condition rows must match)
            selectionArgs,      // selection args - can be provided separately and subbed into selection.
            null);   // string specifying sort order

if (cursor.getCount() == 0) {
  return;
}
Log.i("Count:", Integer.toString(cursor.getCount())); // returns number of names on phone

while (cursor.moveToNext()) {
  // Behold, the firehose!
  Log.d(TAG, "-------------------new record\n");
  for(String column : cursor.getColumnNames()) {
    Log.d(TAG, column + ": " + cursor.getString(cursor.getColumnIndex(column)) + "\n");
  }
}

0voto

Abhishek Punkte 686

Versuchen Sie dies,

public void onActivityResult(int reqCode, int resultCode, Intent data) { super.onActivityResult(reqCode, resultCode, data);

    try {
        if (resultCode == Activity.RESULT_OK) {
            Uri contactData = data.getData();
            Cursor cur = managedQuery(contactData, null, null, null, null);
            ContentResolver contect_resolver = getContentResolver();

            if (cur.moveToFirst()) {
                String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
                String name = "";
                String no = "";

                Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);

                if (phoneCur.moveToFirst()) {
                    name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }

                Log.e("Phone no & name :***: ", name + " : " + no);
                txt.append(name + " : " + no + "\n");

                id = null;
                name = null;
                no = null;
                phoneCur = null;
            }
            contect_resolver = null;
            cur = null;
            //                      populateContacts();
        }
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        Log.e("IllegalArgumentException::", e.toString());
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Error :: ", e.toString());
    }
}

0voto

android developer Punkte 111449

Ich habe hier verschiedene Lösungen kombiniert, und da es in den Ergebnissen doppelte Datensätze gibt (aufgrund mehrerer Konten), habe ich beschlossen, eine Funktion zu erstellen, die häufige Kontotypen gegenüber anderen bevorzugt. In diesem Beispiel ignoriere ich auch die Datensätze mit völlig leeren/nullen Namen (wenn alle so heißen), aber Sie können dies ändern, wenn Sie möchten:

@RequiresPermission(
    allOf = [Manifest.permission.READ_CONTACTS])
@WorkerThread
fun getContactIdToContactNameMap(context: Context): LongSparseArray<ContactObject> {
    val contactIdToContactObjectMap = LongSparseArray<ContactObject>()
    val contentResolver = context.contentResolver
    contentResolver.query(ContactsContract.Data.CONTENT_URI,
        arrayOf(
            ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID,
            ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
            ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
            ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME,
            ContactsContract.RawContacts.ACCOUNT_TYPE),
        ContactsContract.Data.MIMETYPE + " = ? AND " + ContactsContract.Data.IN_VISIBLE_GROUP + " = ?",
        arrayOf(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, "1"),
        null)?.use { cursor ->
        //            Log.d("AppLog", "got ${cursor.count} records for names")
        val colContactId = cursor.getColumnIndex(
            ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID)
        val colFirstName = cursor.getColumnIndex(
            ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME)
        val colFamilyName = cursor.getColumnIndex(
            ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME)
        val colMiddleName = cursor.getColumnIndex(
            ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME)
        val colAccountType =
            cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)
        val googleAccount = "com.google"
        //https://stackoverflow.com/a/44802016/878126
        val prioritizedAccountTypes =
            hashSetOf("vnd.sec.contact.phone", "com.htc.android.pcsc",
                "com.sonyericsson.localcontacts", "com.lge.sync", "com.lge.phone",
                "vnd.tmobileus.contact.phone", "com.android.huawei.phone",
                "Local Phone Account",
                "")
        val contactIdToAccountTypeMap = LongSparseArray<String>()
        while (cursor.moveToNext()) {
            val contactId = cursor.getLong(colContactId)
            val accountType = cursor.getString(colAccountType).orEmpty()
            val existingContact = contactIdToContactObjectMap.get(contactId)
            if (existingContact != null) {
                //this can occur, as we go over all of the items, including duplicate ones made by various sources
                //                        https://stackoverflow.com/a/4599474/878126
                val previousAccountType = contactIdToAccountTypeMap.get(contactId)
                //google account is most prioritized, so we skip current one if previous was of it
                if (previousAccountType == googleAccount)
                    continue
                if (accountType != googleAccount && previousAccountType != null && prioritizedAccountTypes.contains(
                        previousAccountType))
                //we got now a name of an account that isn't prioritized, but we already had a prioritized one, so ignore
                    continue
            }
            contactIdToAccountTypeMap.put(contactId, accountType)
            val firstName = cursor.getString(colFirstName)?.trim()
            val lastName = cursor.getString(colFamilyName)?.trim()
            val middleName = cursor.getString(colMiddleName)?.trim()
            if (firstName.isNullOrBlank() && lastName.isNullOrBlank() && middleName.isNullOrBlank())
                continue
            val contactObject = existingContact ?: ContactObject()
            contactObject.firstName = firstName
            contactObject.lastName = lastName
            contactObject.middleName = middleName
            contactIdToContactObjectMap.put(contactId, contactObject)
        }
    }
    return contactIdToContactObjectMap
}

class ContactObject {
    var firstName: String? = null
    var middleName: String? = null
    var lastName: String? = null
}

Verwendung:

thread {
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
        val contactIdToContactNameMap = getContactIdToContactNameMap(this)
        Log.d("AppLog", "found ${contactIdToContactNameMap.size()} names for contacts")
    } else Log.d("AppLog", "no contacts permission...")
}

-2voto

Hier gibt es einen Beispielcode für genau das: http://developer.Android.com/guide/topics/ui/layout/listview.html

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X