在android中添加联系人照片

时间:2012-09-14 11:30:03

标签: android contacts photo

我想在android联系人列表中添加一个联系人。我能够成功传递联系人号码,姓名和其他详细信息。我面临着个人资料pic的问题。如何通过联系人的个人资料照片?< / p>

2 个答案:

答案 0 :(得分:2)

您必须在传统插页中使用ContactsContract.CommonDataKinds.Photo或使用ContentProviderOperation并提供照片(例如,作为字节数组)。有关示例,请参阅official doc

使用ContentValues的代码基本上类似于:

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 );

使用ContentProviderOperation,代码类似于:

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();

答案 1 :(得分:1)

尝试使用此处添加联系人照片和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);
        }

    }