如何通过 Android 手机联系人列表中的代码添加联系人详细信息..?

发布于 2024-11-14 09:52:50 字数 8445 浏览 2 评论 0原文

**我尝试了这段代码。它运行正常,没有任何错误。但是在createContact方法之后我打开了android的联系人应用程序。我使用 createContact 添加的联系人不存在。当我单击“显示联系人”时,它正在显示。

实际上是什么问题?**

如果您有其他代码,请发布它......

import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.database.Cursor;

import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class NativeContentProvider extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nativecontentprovider);

        Button view = (Button)findViewById(R.id.viewButton);
        Button add = (Button)findViewById(R.id.createButton);
        Button modify = (Button)findViewById(R.id.updateButton);
        Button delete = (Button)findViewById(R.id.deleteButton);


        view.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                displayContacts();
                Log.i("NativeContentProvider", "Completed Displaying Contact list");
            }
        });

        add.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                createContact("Mangesh Joshi", "123456789");
                Log.i("NativeContentProvider", "Created a new contact, of course hard-coded");
            }
        });

        modify.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                updateContact("Sample Name", "987654321");
                Log.i("NativeContentProvider", "Completed updating the email id, if applicable");
            }
        });

        delete.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                deleteContact("Sample Name");
                Log.i("NativeContentProvider", "Deleted the just created contact");
            }
        });
}

private void displayContacts() {

    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(cur.getString(
                    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));
                     Toast.makeText(NativeContentProvider.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
                 } 
            pCur.close();
        }
        }
    }
}

private void createContact(String name, String phone) {
    ContentResolver cr = getContentResolver();

    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String existName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (existName.contains(name)) {
                Toast.makeText(NativeContentProvider.this,"The contact name: " + name + " already exists", Toast.LENGTH_SHORT).show();
                return;                 
            }
        }
    }

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Contacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "[email protected]")
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "com.google")
            .build());

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Contacts.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
            .build());

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Contacts.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
            .build());


    try {
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Toast.makeText(NativeContentProvider.this, "Created a new contact with name: " + name + " and Phone No: " + phone, Toast.LENGTH_SHORT).show();

}

private void updateContact(String name, String phone) {
    ContentResolver cr = getContentResolver();

    String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " + 
                ContactsContract.Data.MIMETYPE + " = ? AND " +
                String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";
    String[] params = new String[] {name,
            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
            String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)};

    Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI, null, where, params, null);

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    if ( (null == phoneCur)  ) {
        createContact(name, phone);
    } else {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(where, params)
                .withValue(ContactsContract.CommonDataKinds.Phone.DATA, phone)
                .build());
    }

    phoneCur.close();

    try {
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Toast.makeText(NativeContentProvider.this, "Updated the phone number of 'Sample Name' to: " + phone, Toast.LENGTH_SHORT).show();
}

private void deleteContact(String name) {

    ContentResolver cr = getContentResolver();
    String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
    String[] params = new String[] {name};

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
            .withSelection(where, params)
            .build());
    try {
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Toast.makeText(NativeContentProvider.this, "Deleted the contact with name '" + name +"'", Toast.LENGTH_SHORT).show();

}
}

**I tried this code. It's working without any error. But after createContact method I opened the android's contacts application. The contact I added using createContact is not there. When I click display contacts, it is displaying.

Actually what is the problem?**

if you have another code please post it ...

import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.database.Cursor;

import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class NativeContentProvider extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nativecontentprovider);

        Button view = (Button)findViewById(R.id.viewButton);
        Button add = (Button)findViewById(R.id.createButton);
        Button modify = (Button)findViewById(R.id.updateButton);
        Button delete = (Button)findViewById(R.id.deleteButton);


        view.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                displayContacts();
                Log.i("NativeContentProvider", "Completed Displaying Contact list");
            }
        });

        add.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                createContact("Mangesh Joshi", "123456789");
                Log.i("NativeContentProvider", "Created a new contact, of course hard-coded");
            }
        });

        modify.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                updateContact("Sample Name", "987654321");
                Log.i("NativeContentProvider", "Completed updating the email id, if applicable");
            }
        });

        delete.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                deleteContact("Sample Name");
                Log.i("NativeContentProvider", "Deleted the just created contact");
            }
        });
}

private void displayContacts() {

    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(cur.getString(
                    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));
                     Toast.makeText(NativeContentProvider.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
                 } 
            pCur.close();
        }
        }
    }
}

private void createContact(String name, String phone) {
    ContentResolver cr = getContentResolver();

    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String existName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (existName.contains(name)) {
                Toast.makeText(NativeContentProvider.this,"The contact name: " + name + " already exists", Toast.LENGTH_SHORT).show();
                return;                 
            }
        }
    }

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Contacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "[email protected]")
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "com.google")
            .build());

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Contacts.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
            .build());

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Contacts.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
            .withValue(ContactsContract.Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
            .build());


    try {
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Toast.makeText(NativeContentProvider.this, "Created a new contact with name: " + name + " and Phone No: " + phone, Toast.LENGTH_SHORT).show();

}

private void updateContact(String name, String phone) {
    ContentResolver cr = getContentResolver();

    String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " + 
                ContactsContract.Data.MIMETYPE + " = ? AND " +
                String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";
    String[] params = new String[] {name,
            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
            String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)};

    Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI, null, where, params, null);

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    if ( (null == phoneCur)  ) {
        createContact(name, phone);
    } else {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(where, params)
                .withValue(ContactsContract.CommonDataKinds.Phone.DATA, phone)
                .build());
    }

    phoneCur.close();

    try {
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Toast.makeText(NativeContentProvider.this, "Updated the phone number of 'Sample Name' to: " + phone, Toast.LENGTH_SHORT).show();
}

private void deleteContact(String name) {

    ContentResolver cr = getContentResolver();
    String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
    String[] params = new String[] {name};

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
            .withSelection(where, params)
            .build());
    try {
        cr.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Toast.makeText(NativeContentProvider.this, "Deleted the contact with name '" + name +"'", Toast.LENGTH_SHORT).show();

}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小巷里的女流氓 2024-11-21 09:52:50
import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Toast;

public class AddContacts extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    /*    try
        {
            ContentResolver cr = this.getContentResolver();
            ContentValues cv = new ContentValues();
            cv.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, "New Name");
            cv.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "1234567890");
            cv.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
            cr.insert(ContactsContract.RawContacts.CONTENT_URI, cv);

            Toast.makeText(this, "Contact added", Toast.LENGTH_LONG).show();
        }
        catch(Exception e)
        {
            TextView tv = new TextView(this);
            tv.setText(e.toString());
            setContentView(tv);
        }
*/        
        String DisplayName = "XYZ";
        String MobileNumber = "123456";
        String HomeNumber = "1111";
        String WorkNumber = "2222";
        String emailID = "[email protected]";
        String company = "bad";
        String jobTitle = "abcd";


                           ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
                           ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                                   .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                                   .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                                   .build());

                           //------------------------------------------------------ Names
                           if(DisplayName != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DisplayName).build());
                           }                       
                           //------------------------------------------------------ Mobile Number
                           if(MobileNumber != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
                                               ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                                       .build());
                           }

                           //------------------------------------------------------ Home Numbers
                           if(HomeNumber != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, HomeNumber)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
                                               ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
                                       .build());
                           }

                           //------------------------------------------------------ Work Numbers
                           if(WorkNumber != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, WorkNumber)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
                                               ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
                                       .build());
                           }

                           //------------------------------------------------------ Email
                           if(emailID != null)
                           {
                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                           .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                           .withValue(ContactsContract.Data.MIMETYPE,
                                                   ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                                           .withValue(ContactsContract.CommonDataKinds.Email.DATA, emailID)
                                           .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
                                           .build());
                           }

                           //------------------------------------------------------ Organization
                           if(!company.equals("") && !jobTitle.equals(""))
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                                       .build());
                           }

                           // Asking the Contact provider to create a new contact                  
                           try 
                           {
                               getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                           } 
                           catch (Exception e) 
                           {               
                               e.printStackTrace();
                               Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                           }



    }
}
import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Toast;

public class AddContacts extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    /*    try
        {
            ContentResolver cr = this.getContentResolver();
            ContentValues cv = new ContentValues();
            cv.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, "New Name");
            cv.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "1234567890");
            cv.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
            cr.insert(ContactsContract.RawContacts.CONTENT_URI, cv);

            Toast.makeText(this, "Contact added", Toast.LENGTH_LONG).show();
        }
        catch(Exception e)
        {
            TextView tv = new TextView(this);
            tv.setText(e.toString());
            setContentView(tv);
        }
*/        
        String DisplayName = "XYZ";
        String MobileNumber = "123456";
        String HomeNumber = "1111";
        String WorkNumber = "2222";
        String emailID = "[email protected]";
        String company = "bad";
        String jobTitle = "abcd";


                           ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
                           ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                                   .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                                   .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                                   .build());

                           //------------------------------------------------------ Names
                           if(DisplayName != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DisplayName).build());
                           }                       
                           //------------------------------------------------------ Mobile Number
                           if(MobileNumber != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
                                               ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                                       .build());
                           }

                           //------------------------------------------------------ Home Numbers
                           if(HomeNumber != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, HomeNumber)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
                                               ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
                                       .build());
                           }

                           //------------------------------------------------------ Work Numbers
                           if(WorkNumber != null)
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, WorkNumber)
                                       .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
                                               ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
                                       .build());
                           }

                           //------------------------------------------------------ Email
                           if(emailID != null)
                           {
                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                           .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                           .withValue(ContactsContract.Data.MIMETYPE,
                                                   ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                                           .withValue(ContactsContract.CommonDataKinds.Email.DATA, emailID)
                                           .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
                                           .build());
                           }

                           //------------------------------------------------------ Organization
                           if(!company.equals("") && !jobTitle.equals(""))
                           {
                               ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                       .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                       .withValue(ContactsContract.Data.MIMETYPE,
                                               ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
                                       .withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
                                       .build());
                           }

                           // Asking the Contact provider to create a new contact                  
                           try 
                           {
                               getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                           } 
                           catch (Exception e) 
                           {               
                               e.printStackTrace();
                               Toast.makeText(getApplicationContext(), "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                           }



    }
}
风吹雨成花 2024-11-21 09:52:50

确保您已启用联系人列表的显示选项。联系人列表>菜单选项>显示选项>在您的帐户上打勾

Make sure that you have enabled display options of the contact list.contact list>menu option>display option> tick on your account

舟遥客 2024-11-21 09:52:50
    insertContact(getContentResolver(),editTextName.getText().toString(),editTextPhone.getText().toString());
    //if (checkBoxSelf.isChecked()){
      //  Toast.makeText(getApplicationContext(), "Self", Toast.LENGTH_SHORT).show();
   // }else {
    //    Toast.makeText(getApplicationContext(), "Other", Toast.LENGTH_SHORT).show();
    //}

    // Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(this, AllCardsActivity.class);
    startActivity(intent);

    //hideProgressBar();
    finish();
}

public static boolean insertContact(ContentResolver contentResolver,String firstName, String mobileNumber) {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,firstName).build());

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,mobileNumber).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
    try {
        contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
        return false;
    }
    return true;

// 工作代码只需要获得应用程序的许可

    insertContact(getContentResolver(),editTextName.getText().toString(),editTextPhone.getText().toString());
    //if (checkBoxSelf.isChecked()){
      //  Toast.makeText(getApplicationContext(), "Self", Toast.LENGTH_SHORT).show();
   // }else {
    //    Toast.makeText(getApplicationContext(), "Other", Toast.LENGTH_SHORT).show();
    //}

    // Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(this, AllCardsActivity.class);
    startActivity(intent);

    //hideProgressBar();
    finish();
}

public static boolean insertContact(ContentResolver contentResolver,String firstName, String mobileNumber) {
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,firstName).build());

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,mobileNumber).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
    try {
        contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (Exception e) {
        return false;
    }
    return true;

// Working code only needs to take permission from app

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文