Add Contact photo in android

不打扰是莪最后的温柔 提交于 2020-01-15 04:29:47

问题


I want to add a contact in the android contacts list.I am able to pass the contact no,name and other detail successfully.I am facing problem with the profile pic.How to pass a profile pic for the contact ?


回答1:


You have to use ContactsContract.CommonDataKinds.Photo in your traditional insert or using ContentProviderOperation and also provide the photo (as a byte array for example). Just refer to the official doc for some examples.

Basically the code with using ContentValues will look something like:

ContentValues values = new ContentValues();
values.put(ContactsContract.Data.RAW_CONTACT_ID, contactId);
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, photoByteArray);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE );

Using ContentProviderOperation, the code will look similar to:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
 ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
  .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
  .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
  .withValue(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE,photoByteArray).build();



回答2:


Try this to Add contact with photo and ListContact..

AddContact..

    public class AddContact extends ActionBarActivity {

        ImageView img;
        Bitmap contact_bitmap;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_add);

            img = (ImageView) findViewById(R.id.imageView1);
            img.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    selectImage();
                }
            });

            Button addconatct = (Button) findViewById(R.id.btn_addcontact);
            addconatct.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    EditText e1 = (EditText) findViewById(R.id.editText1);

                    EditText e2 = (EditText) findViewById(R.id.editText2);

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

                    int rawContactID = ops.size();

                    // Adding insert operation to operations list
                    // to insert a new raw contact in the table
                    // ContactsContract.RawContacts
                    ops.add(ContentProviderOperation
                            .newInsert(ContactsContract.RawContacts.CONTENT_URI)
                            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE,
                                    null).withValue(RawContacts.ACCOUNT_NAME, null)
                            .build());

                    // Adding insert operation to operations list
                    // to insert display name in the table ContactsContract.Data
                    ops.add(ContentProviderOperation
                            .newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(
                                    ContactsContract.Data.RAW_CONTACT_ID,
                                    rawContactID)
                            .withValue(ContactsContract.Data.MIMETYPE,
                                    StructuredName.CONTENT_ITEM_TYPE)
                            .withValue(StructuredName.DISPLAY_NAME,
                                    e1.getText().toString()).build());

                    // Adding insert operation to operations list
                    // to insert Mobile Number in the table ContactsContract.Data
                    ops.add(ContentProviderOperation
                            .newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValueBackReference(
                                    ContactsContract.Data.RAW_CONTACT_ID,
                                    rawContactID)
                            .withValue(ContactsContract.Data.MIMETYPE,
                                    Phone.CONTENT_ITEM_TYPE)
                            .withValue(Phone.NUMBER, e2.getText().toString())
                            .withValue(Phone.TYPE,
                                    CommonDataKinds.Phone.TYPE_MOBILE).build());

                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    if (contact_bitmap != null) { // If an image is selected
                                                    // successfully
                        contact_bitmap.compress(Bitmap.CompressFormat.PNG, 75,
                                stream);

                        // Adding insert operation to operations list
                        // to insert Photo in the table ContactsContract.Data
                        ops.add(ContentProviderOperation
                                .newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValueBackReference(
                                        ContactsContract.Data.RAW_CONTACT_ID,
                                        rawContactID)
                                .withValue(ContactsContract.Data.IS_SUPER_PRIMARY,
                                        1)
                                .withValue(ContactsContract.Data.MIMETYPE,
                                        Photo.CONTENT_ITEM_TYPE)
                                .withValue(
                                        ContactsContract.CommonDataKinds.Photo.PHOTO,
                                        stream.toByteArray()).build());

                        try {
                            stream.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        // Executing all the insert operations as a single database
                        // transaction
                        getContentResolver().applyBatch(ContactsContract.AUTHORITY,
                                ops);
                        Toast.makeText(getBaseContext(),
                                "Contact is successfully added", Toast.LENGTH_SHORT)
                                .show();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    } catch (OperationApplicationException e) {
                        e.printStackTrace();
                    }

                }
            });

        }

        private void selectImage() {

            final CharSequence[] options = { "Take Photo", "Choose from Gallery",
                    "Cancel" };

            AlertDialog.Builder builder = new AlertDialog.Builder(AddContact.this);
            builder.setTitle("Add Photo!");
            builder.setItems(options, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals("Take Photo")) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        File f = new File(android.os.Environment
                                .getExternalStorageDirectory(), "temp.jpg");
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                        startActivityForResult(intent, 1);
                    } else if (options[item].equals("Choose from Gallery")) {
                        Intent intent = new Intent(
                                Intent.ACTION_PICK,
                                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, 2);

                    } else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
            if (resultCode == RESULT_OK) {
                if (requestCode == 1) {
                    File f = new File(Environment.getExternalStorageDirectory()
                            .toString());
                    for (File temp : f.listFiles()) {
                        if (temp.getName().equals("temp.jpg")) {
                            f = temp;
                            break;
                        }
                    }
                    try {
                        Bitmap bitmap;
                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                        bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                                bitmapOptions);

                        contact_bitmap = bitmap;

                        img.setImageBitmap(bitmap);

                        String path = android.os.Environment
                                .getExternalStorageDirectory()
                                + File.separator
                                + "Phoenix" + File.separator + "default";
                        f.delete();
                        OutputStream outFile = null;
                        File file = new File(path, String.valueOf(System
                                .currentTimeMillis()) + ".jpg");
                        try {
                            outFile = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                            outFile.flush();
                            outFile.close();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (requestCode == 2) {

                    Uri selectedImage = data.getData();
                    String[] filePath = { MediaStore.Images.Media.DATA };
                    Cursor c = getContentResolver().query(selectedImage, filePath,
                            null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePath[0]);
                    String picturePath = c.getString(columnIndex);
                    c.close();
                    Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                    Log.w("path of image from gallery......******************.........",
                            picturePath + "");
                    contact_bitmap = thumbnail;
                    img.setImageBitmap(thumbnail);
                }
            }
        }

    }

ListContact with image..

    public class ListContact extends ActionBarActivity {

        ListView list;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_list);

            list = (ListView) findViewById(R.id.listView1);

            list.setAdapter(new ContactListAdapter(ListContact.this));

        }

        public class ContactListAdapter extends BaseAdapter {

            Activity acvtivity_ab;

            String phoneNumber = null;
            String email = null;

            Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
            String _ID = ContactsContract.Contacts._ID;
            String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
            String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

            String PHOTO_URL = ContactsContract.Contacts.PHOTO_THUMBNAIL_URI;

            ContentResolver contentResolver = getContentResolver();

            Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
                    null);

            public ContactListAdapter(ListContact listContact) {
                // TODO Auto-generated constructor stub
                acvtivity_ab = listContact;
            }

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return cursor.getCount();
            }

            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public long getItemId(int position) {
                // TODO Auto-generated method stub
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                // TODO Auto-generated method stub

                View v;
                LayoutInflater inflater = (LayoutInflater) acvtivity_ab
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                v = inflater.inflate(R.layout.list_row, null);

                if (cursor != null && cursor.getCount() > 0
                        && position < cursor.getCount()
                        && position != cursor.getCount()) {
                    cursor.moveToPosition(position);
                    String contact_id = cursor
                            .getString(cursor.getColumnIndex(_ID));
                    long contactId = Long.parseLong(contact_id);
                    String name = cursor.getString(cursor
                            .getColumnIndex(DISPLAY_NAME));
                    String photo = cursor.getString(cursor
                            .getColumnIndex(PHOTO_URL));
                    TextView t_name = (TextView) v.findViewById(R.id.textView1);

                    t_name.setText(name);

                    Uri my_contact_Uri = Uri.withAppendedPath(
                            ContactsContract.Contacts.CONTENT_URI,
                            String.valueOf(contact_id));

                    InputStream inputStream = ContactsContract.Contacts
                            .openContactPhotoInputStream(getContentResolver(),
                                    my_contact_Uri);
                    BufferedInputStream buf = new BufferedInputStream(inputStream);
                    Bitmap my_btmp = BitmapFactory.decodeStream(buf);

                    if (my_btmp != null) {

                        Log.i("test", name + ":::" + photo + "::??" + "Posi"
                                + position);
                        ImageView img_thumb = (ImageView) v
                                .findViewById(R.id.image_list);
                        img_thumb.setImageBitmap(loadContactPhoto(contentResolver,
                                contactId));

                    }

                } else {
                    Log.i("test", "else call");
                }

                return v;
            }

        }

        public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
            Uri uri = ContentUris.withAppendedId(
                    ContactsContract.Contacts.CONTENT_URI, id);
            InputStream input = ContactsContract.Contacts
                    .openContactPhotoInputStream(cr, uri);
            if (input == null) {
                return null;
            }
            return BitmapFactory.decodeStream(input);
        }

    }


来源:https://stackoverflow.com/questions/12423642/add-contact-photo-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!