如何在Android Studio中更新联系人的电话号码。

huangapple go评论76阅读模式
英文:

How can I update the phone numbers of contacts in Android Studios

问题

我是新手,正在使用Android Studio开发应用程序,并决定制作一个应用程序来编辑我的手机联系人的电话号码,作为我的第一个测试应用程序。

我使用一个类来获取有关我手机上所有联系人的信息,然后我创建了一个ListView,显示联系人的姓名、ID、头像和已注册的电话号码。

信息已从ContactsContract.Contacts表中获取。到目前为止,一切都运行良好。

但现在我必须编辑所有联系人的电话号码,但我不知道如何确切地做到这一点。我一直在查阅Android开发者文档,但找不到可以帮助我的东西。在这种情况下,我不想使用Intent。

我有这个用于获取所有联系人信息的Kotlin类:

@file:Suppress("unused")
package com.example.uimx
import android.Manifest
import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.provider.ContactsContract
import androidx.annotation.RequiresPermission

@RequiresPermission(Manifest.permission.READ_CONTACTS)
fun Context.isContactExists(
        phoneNumber: String
): Boolean {
    val lookupUri = Uri.withAppendedPath(
            ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(phoneNumber)
    )
    val projection = arrayOf(
            ContactsContract.PhoneLookup._ID,
            ContactsContract.PhoneLookup.NUMBER,
            ContactsContract.PhoneLookup.DISPLAY_NAME
    )
    contentResolver.query(lookupUri, projection, null, null, null).use {
        return (it?.moveToFirst() == true)
    }
}

@RequiresPermission(Manifest.permission.READ_CONTACTS)
@JvmOverloads
fun Context.retrieveAllContacts(
        searchPattern: String = "",
        retrieveAvatar: Boolean = true,
        limit: Int = -1,
        offset: Int = -1
): List<ContactData> {
    val result: MutableList<ContactData> = mutableListOf()
    contentResolver.query(
            ContactsContract.Contacts.CONTENT_URI,
            CONTACT_PROJECTION,
            if (searchPattern.isNotBlank()) "${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY} LIKE '%$searchPattern%'" else null,
            if (searchPattern.isNotBlank()) arrayOf(searchPattern) else null,
            if (limit > 0 && offset > -1) "${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY} ASC LIMIT $limit OFFSET $offset"
            else ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " ASC"
    )?.use {
        if (it.moveToFirst()) {
            do {
                val contactId = it.getLong(it.getColumnIndex(CONTACT_PROJECTION[0]))
                val name = it.getString(it.getColumnIndex(CONTACT_PROJECTION[2])) ?: ""
                val hasPhoneNumber = it.getString(it.getColumnIndex(CONTACT_PROJECTION[3])).toInt()
                val phoneNumber: List<String> = if (hasPhoneNumber > 0) {
                    retrievePhoneNumber(contactId)
                } else mutableListOf()

                val avatar = if (retrieveAvatar) retrieveAvatar(contactId) else null
                result.add(ContactData(contactId, name, phoneNumber, avatar))
            } while (it.moveToNext())
        }
    }
    return result
}

private fun Context.retrievePhoneNumber(contactId: Long): List<String> {
    val result: MutableList<String> = mutableListOf()
    contentResolver.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null,
            "${ContactsContract.CommonDataKinds.Phone.CONTACT_ID} =?",
            arrayOf(contactId.toString()),
            null
    )?.use {
        if (it.moveToFirst()) {
            do {
                result.add(it.getString(it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)))
            } while (it.moveToNext())
        }
    }
    return result
}

private fun Context.retrieveAvatar(contactId: Long): Uri? {
    return contentResolver.query(
            ContactsContract.Data.CONTENT_URI,
            null,
            "${ContactsContract.Data.CONTACT_ID} =? AND ${ContactsContract.Data.MIMETYPE} = '${ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE}'",
            arrayOf(contactId.toString()),
            null
    )?.use {
        if (it.moveToFirst()) {
            val contactUri = ContentUris.withAppendedId(
                    ContactsContract.Contacts.CONTENT_URI,
                    contactId
            )
            Uri.withAppendedPath(
                    contactUri,
                    ContactsContract.Contacts.Photo.CONTENT_DIRECTORY
            )
        } else null
    }
}

private val CONTACT_PROJECTION = arrayOf(
        ContactsContract.Contacts._ID,
        ContactsContract.Contacts.LOOKUP_KEY,
        ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
        ContactsContract.Contacts.HAS_PHONE_NUMBER
)

data class ContactData(
        val contactId: Long,
        val name: String,
        val phoneNumber: List<String>,
        val avatar: Uri?
)

我有一个准备好接收点击事件的按钮,并调用一个函数,该函数将包含用于替换所有联系人的电话号码的脚本,我将为每个联系人定义新的电话号码。

我有下面这段代码,是我从互联网上找到的,但无法在我的应用程序中使其工作:

private int  updateContactPhoneByID(long rawContactId)
{
    int ret = 0;

    ContentResolver contentResolver = getContentResolver();

    // Update data table phone number use contact raw contact id.
    if(rawContactId > -1) {
        // Update mobile phone number.
        updatePhoneNumber(contentResolver, rawContactId, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE, "66666666666666");

        // Update work mobile phone number.
        updatePhoneNumber(contentResolver, rawContactId, ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE, "8888888888888888");

        // Update home phone number.
        updatePhoneNumber(contentResolver, rawContactId, ContactsContract.CommonDataKinds.Phone.TYPE_HOME, "99999999999999999");

        ret = 1;
    }else
    {
        ret = 0;
    }

    return ret;
}

/* Update phone number with raw contact id and phone type.*/
private void updatePhoneNumber(ContentResolver contentResolver, long rawContactId, int phoneType, String newPhoneNumber)
{
    // Create content values object.
    ContentValues contentValues = new ContentValues();

    // Put new phone number value.
    contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, newPhoneNumber);

    // Create query condition, query with the raw contact id.
    StringBuffer whereClauseBuf = new StringBuffer();

    // Specify the update contact id.
    whereClauseBuf.append(ContactsContract.Data.RAW_CONTACT_ID);
    whereClauseBuf.append("=");
    whereClauseBuf.append(rawContactId);

    // Specify the row data mimetype to phone mimetype( vnd.android.cursor.item/phone_v2 )
    whereClauseBuf.append(" and ");
    whereClauseBuf.append(ContactsContract.Data.MIMETYPE);
    whereClauseBuf.append(" = '");
    String mimetype = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
    whereClauseBuf.append(mimetype);
    whereClauseBuf.append("'");

    // Specify phone type.
    whereClauseBuf.append(" and ");
    where

<details>
<summary>英文:</summary>

I am new to developing apps with android studio, and I decided to make an app to edit the phone numbers of my phone contacts as my first test app.

I use a class to get information about all the contacts that I have on my cell phone, then I have created a listview where I show the contact&#39;s name, ID, avatar and registered phone numbers. 

The information has been gotten from the ContactsContract.Contacts table. This all works fine, so far.

But now I have to edit the phone numbers of all the contacts, but I don&#39;t know exactly how to do it. I&#39;ve been going through the Android devs documentation but I can&#39;t get anything that can help me. I don&#39;t want to use Intent in this case.

I have this kotlin class that I use to get the information of all contacts is this:

    @file:Suppress(&quot;unused&quot;)
		package com.example.uimx
		import android.Manifest
		import android.content.ContentUris
		import android.content.Context
		import android.net.Uri
		import android.provider.ContactsContract
		import androidx.annotation.RequiresPermission

		@RequiresPermission(Manifest.permission.READ_CONTACTS)
		fun Context.isContactExists(
		        phoneNumber: String
		): Boolean {
		    val lookupUri = Uri.withAppendedPath(
		            ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
		            Uri.encode(phoneNumber)
		    )
		    val projection = arrayOf(
		            ContactsContract.PhoneLookup._ID,
		            ContactsContract.PhoneLookup.NUMBER,
		            ContactsContract.PhoneLookup.DISPLAY_NAME
		    )
		    contentResolver.query(lookupUri, projection, null, null, null).use {
		        return (it?.moveToFirst() == true)
		    }
		}

		@RequiresPermission(Manifest.permission.READ_CONTACTS)
		@JvmOverloads
		fun Context.retrieveAllContacts(
		        searchPattern: String = &quot;&quot;,
		        retrieveAvatar: Boolean = true,
		        limit: Int = -1,
		        offset: Int = -1
		): List&lt;ContactData&gt; {
		    val result: MutableList&lt;ContactData&gt; = mutableListOf()
		    contentResolver.query(
		            ContactsContract.Contacts.CONTENT_URI,
		            CONTACT_PROJECTION,
		            if (searchPattern.isNotBlank()) &quot;${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY} LIKE &#39;%?%&#39;&quot; else null,
		            if (searchPattern.isNotBlank()) arrayOf(searchPattern) else null,
		            if (limit &gt; 0 &amp;&amp; offset &gt; -1) &quot;${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY} ASC LIMIT $limit OFFSET $offset&quot;
		            else ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + &quot; ASC&quot;
		    )?.use {
		        if (it.moveToFirst()) {
		            do {
		                val contactId = it.getLong(it.getColumnIndex(CONTACT_PROJECTION[0]))
		                val name = it.getString(it.getColumnIndex(CONTACT_PROJECTION[2])) ?: &quot;&quot;
		                val hasPhoneNumber = it.getString(it.getColumnIndex(CONTACT_PROJECTION[3])).toInt()
		                val phoneNumber: List&lt;String&gt; = if (hasPhoneNumber &gt; 0) {
		                    retrievePhoneNumber(contactId)
		                } else mutableListOf()

		                val avatar = if (retrieveAvatar) retrieveAvatar(contactId) else null
		                result.add(ContactData(contactId, name, phoneNumber, avatar))
		            } while (it.moveToNext())
		        }
		    }
		    return result
		}

		private fun Context.retrievePhoneNumber(contactId: Long): List&lt;String&gt; {
		    val result: MutableList&lt;String&gt; = mutableListOf()
		    contentResolver.query(
		            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
		            null,
		            &quot;${ContactsContract.CommonDataKinds.Phone.CONTACT_ID} =?&quot;,
		            arrayOf(contactId.toString()),
		            null
		    )?.use {
		        if (it.moveToFirst()) {
		            do {
		                result.add(it.getString(it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)))
		            } while (it.moveToNext())
		        }
		    }
		    return result
		}

		private fun Context.retrieveAvatar(contactId: Long): Uri? {
		    return contentResolver.query(
		            ContactsContract.Data.CONTENT_URI,
		            null,
		            &quot;${ContactsContract.Data.CONTACT_ID} =? AND ${ContactsContract.Data.MIMETYPE} = &#39;${ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE}&#39;&quot;,
		            arrayOf(contactId.toString()),
		            null
		    )?.use {
		        if (it.moveToFirst()) {
		            val contactUri = ContentUris.withAppendedId(
		                    ContactsContract.Contacts.CONTENT_URI,
		                    contactId
		            )
		            Uri.withAppendedPath(
		                    contactUri,
		                    ContactsContract.Contacts.Photo.CONTENT_DIRECTORY
		            )
		        } else null
		    }
		}

		private val CONTACT_PROJECTION = arrayOf(
		        ContactsContract.Contacts._ID,
		        ContactsContract.Contacts.LOOKUP_KEY,
		        ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
		        ContactsContract.Contacts.HAS_PHONE_NUMBER
		)

		data class ContactData(
		        val contactId: Long,
		        val name: String,
		        val phoneNumber: List&lt;String&gt;,
		        val avatar: Uri?
		)


I have a button prepared that receives the click event and calls a function that would have the script to replace all the phone numbers of all the contacts, for new phone numbers that I will define for each contact.

I have this next code that I got on the internet but I can&#39;t get it to work in my app.

    private int  updateContactPhoneByID(long rawContactId)
	{
	    int ret = 0;

	    ContentResolver contentResolver = getContentResolver();

	    // Update data table phone number use contact raw contact id.
	    if(rawContactId &gt; -1) {
	        // Update mobile phone number.
	        updatePhoneNumber(contentResolver, rawContactId, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE, &quot;66666666666666&quot;);

	        // Update work mobile phone number.
	        updatePhoneNumber(contentResolver, rawContactId, ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE, &quot;8888888888888888&quot;);

	        // Update home phone number.
	        updatePhoneNumber(contentResolver, rawContactId, ContactsContract.CommonDataKinds.Phone.TYPE_HOME, &quot;99999999999999999&quot;);

	        ret = 1;
	    }else
	    {
	        ret = 0;
	    }

	    return ret;
	}

	/* Update phone number with raw contact id and phone type.*/
	private void updatePhoneNumber(ContentResolver contentResolver, long rawContactId, int phoneType, String newPhoneNumber)
	{
	    // Create content values object.
	    ContentValues contentValues = new ContentValues();

	    // Put new phone number value.
	    contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, newPhoneNumber);

	    // Create query condition, query with the raw contact id.
	    StringBuffer whereClauseBuf = new StringBuffer();

	    // Specify the update contact id.
	    whereClauseBuf.append(ContactsContract.Data.RAW_CONTACT_ID);
	    whereClauseBuf.append(&quot;=&quot;);
	    whereClauseBuf.append(rawContactId);

	    // Specify the row data mimetype to phone mimetype( vnd.android.cursor.item/phone_v2 )
	    whereClauseBuf.append(&quot; and &quot;);
	    whereClauseBuf.append(ContactsContract.Data.MIMETYPE);
	    whereClauseBuf.append(&quot; = &#39;&quot;);
	    String mimetype = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
	    whereClauseBuf.append(mimetype);
	    whereClauseBuf.append(&quot;&#39;&quot;);

	    // Specify phone type.
	    whereClauseBuf.append(&quot; and &quot;);
	    whereClauseBuf.append(ContactsContract.CommonDataKinds.Phone.TYPE);
	    whereClauseBuf.append(&quot; = &quot;);
	    whereClauseBuf.append(phoneType);

	    // Update phone info through Data uri.Otherwise it may throw java.lang.UnsupportedOperationException.
	    Uri dataUri = ContactsContract.Data.CONTENT_URI;

	    // Get update data count.
	    int updateCount = contentResolver.update(dataUri, contentValues, whereClauseBuf.toString(), null);
	}

How to make the above script work to update the correct contact table with the information I have.






</details>


# 答案1
**得分**: 1

我认为您对`contactId``rawContactId`存在一些混淆

当您从设备中读取所有联系人时您会获得该联系人的`contactId`,但您尝试使用的`updateContactPhoneByID`方法需要一个不同的`rawContactId`。

简而言之`ContactsContract.Contacts`表中的每个`Contact`都由多个`RawContacts`组成通常由不同的应用程序或帐户同步例如一个`RawContact`来自您的个人Google帐户另一个`RawContact`来自您的工作Google帐户另一个来自WhatsApp还有一个来自Yahoo),来自所有这些`RawContacts`的详细信息都会合并成一个单独的联系人配置文件

我不确定您希望进行的编辑方式如果一个联系人有多个电话号码您是希望用一个新的电话号码替换所有这些电话还是允许用户在编辑屏幕上输入多个电话号码

无论如何这里有一个小的Kotlin函数它接受一个`contactId`和一个现有的电话号码X然后将该单个号码替换为新号码希望您可以根据自己的需求进行调整

```kotlin
private fun updatePhone(contactId: Long, existingNumber: String, newNumber: String) {
  val contentValues = ContentValues()
  contentValues.put(Phone.NUMBER, newNumber)

  val where = Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "=? AND " + Phone.NUMBER + "=?"
  val whereArgs = arrayOf((contactId).toString(), Phone.CONTENT_ITEM_TYPE, existingNumber)

  contentResolver.update(Data.CONTENT_URI, contentValues, where, whereArgs)
}

请注意,existingNumber参数必须与ContactsContract数据库中的字符串完全匹配。

英文:

I think you have a confusion about contactId and rawContactId.

When you read all the contacts from the device, you're getting the contactId of that contact, but the updateContactPhoneByID method you're trying to use is expecting a rawContactId which is different.

In a nutshell, every Contact in the ContactsContract.Contacts table is comprised out of multiple RawContacts each is usually synced by some different app or account (e.g. one RawContact from your personal Google account, another RawContact from your work Google account, another one from Whatsapp, and one from Yahoo), the details from ALL these RawContacts are join to make up a single contact profile.

I'm not sure how you want the edit to work, if a contact has multiple phone numbers, do you want to replace ALL those phones with a single new phone number, or do you allow the user to type multiple phones in your edit screen?

Anyway, here's a small kotlin function that takes a contactId and an existing phone number X and replaces that single number with a new one.
I hope you can adapt it to your needs.

private fun updatePhone(contactId:Long, existingNumber:String, newNumber:String) {
val contentValues = ContentValues()
contentValues.put(Phone.NUMBER, newNumber)
val where = Data.CONTACT_ID + &quot;=?&quot; + &quot; AND &quot; + Data.MIMETYPE + &quot;=?&quot; + &quot; AND &quot; + Phone.NUMBER + &quot;=?&quot;
val whereArgs = arrayOf&lt;String&gt;((contactId).toString(), Phone.CONTENT_ITEM_TYPE, existingNumber)
contentResolver.update(Data.CONTENT_URI, contentValues, where, whereArgs)
}

Note that the existingNumber param must match the string in the ContactsContract DB exactly.

huangapple
  • 本文由 发表于 2020年9月5日 04:39:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63747783.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定