如何从ImageView的按钮点击更改选定的联系人镜像。 [英] how to change selected contact image on button click from imageview.?

查看:264
本文介绍了如何从ImageView的按钮点击更改选定的联系人镜像。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在主要活动显示联系人列表。现在选择任何接触,并打开Detail.java活动。现在我要设置从次活动的ImageView这个特殊的选定联系人的图像。 mainActivity.java

 公共类MainActivity延伸活动{

SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor;
点阵位图;
@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    //从联系人内容提供商的联系人存储在此游标
    mMatrixCursor =新MatrixCursor(新的String [] {_id,姓名,照片,细节}​​);

    //适配器在列表视图设置数据
    mAdapter =新SimpleCursorAdapter(getBaseContext()
            R.layout.lv_layout,
            空值,
            新的String [] {姓名,照片,详细信息},
            新INT [] {R.id.tv_name,R.id.iv_photo,R.id.tv_details},0);

    //获取引用列表视图
    ListView控件lstContacts =(ListView控件)findViewById(R.id.lst_contacts);

    //设置适配器列表视图
    lstContacts.setAdapter(mAdapter);

    //创建一个AsyncTask的对象来检索和加载列表视图与联系人
    ListViewContactsLoader listViewContactsLoader =新ListViewContactsLoader();

    //启动AsyncTask的过程来检索和加载列表视图与联系人
    listViewContactsLoader.execute();
    lstContacts.setOnItemClickListener(新OnItemClickListener()
    {
          @燮pressWarnings({空,未使用})
        @覆盖
          公共无效onItemClick(适配器视图<>母公司视图中查看,INT位置,长ID)
          {
              ByteArrayOutputStream流=新ByteArrayOutputStream();

             // bitmap.com preSS(Bitmap.Com pressFormat.PNG,100,流);
              字节[]的字节数组= stream.toByteArray();

              意向意图=新的意图(MainActivity.this,detail.class);

            //意向意图=新的意图(Current.this,Next.class);
              intent.putExtra(BMP,字节); //图像
            // intent.putExtra(文字,文本); //文本
              startActivity(意向);
            // startActivity(意向);



          }
    });


}

/ **一个AsyncTask的类来检索和加载列表视图与联系人* /
私有类ListViewContactsLoader扩展的AsyncTask<虚空,虚空,光标> {

    @覆盖
    受保护的光标doInBackground(空... PARAMS){
        乌里contactsUri = ContactsContract.Contacts.CONTENT_URI;

        //查询表ContactsContract.Contacts检索所有联系人
        光标contactsCursor = getContentResolver()查询(contactsUri,NULL,NULL,NULL,
                                ContactsContract.Contacts.DISPLAY_NAME +ASC);

        如果(contactsCursor.moveToFirst()){
            做{
                长的ContactID = contactsCursor.getLong(contactsCursor.getColumnIndex(_ ID));


                乌里dataUri = ContactsContract.Data.CONTENT_URI;

                //查询表ContactsContract.Data检索像单个项目
                //家庭电话,移动电话,工作电子邮件等对应于各接触
                光标dataCursor = getContentResolver()查询(dataUri,空,
                                        ContactsContract.Data.CONTACT_ID +=+的ContactID,
                                        NULL,NULL);



                字符串显示名=;
                字符串nickname =;
                字符串HOMEPHONE =;
                字符串MOBILEPHONE =;
                字符串办公电话=;
                串photoPath =+ R.drawable.blank;
                byte []的photoByte = NULL;

                字符串标题=;



                如果(dataCursor.moveToFirst()){
                    //获取显示名称
                    显示名= dataCursor.getString(da​​taCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
                    做{

                        //获取昵称
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
                            绰号= dataCursor.getString(da​​taCursor.getColumnIndex(数据1));

                        //获取电话号码
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
                            开关(dataCursor.getInt(dataCursor.getColumnIndex(数据2))){
                                案例ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
                                    HOMEPHONE = dataCursor.getString(da​​taCursor.getColumnIndex(数据1));
                                    打破;
                                案例ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
                                    MOBILEPHONE = dataCursor.getString(da​​taCursor.getColumnIndex(数据1));
                                    打破;
                                案例ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
                                    办公电话= dataCursor.getString(da​​taCursor.getColumnIndex(数据1));
                                    打破;
                            }
                        }





                        //获取照片
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){
                            photoByte = dataCursor.getBlob(dataCursor.getColumnIndex(DATA15));

                            如果(photoByte!= NULL){
                                 位= BitmapFactory.de codeByteArray(photoByte,0,photoByte.length);

                                //获取缓存目录
                                文件cacheDirectory = getBaseContext()getCacheDir()。

                                //临时文件来存储接触式图像
                                文件TMPFILE =新的文件(cacheDirectory.getPath()+/wpta_"+contactId+".png);

                                //然后,FileOutputStream临时文件
                                尝试 {
                                    FileOutputStream中fOutStream =新的FileOutputStream(TMPFILE);

                                    //编写位图到临时文件作为PNG文件
                                    bitmap.com preSS(Bitmap.Com pressFormat.PNG,100,fOutStream);

                                    //刷新的FileOutputStream
                                    fOutStream.flush();

                                    //关闭的FileOutputStream
                                    fOutStream.close();

                                }赶上(例外五){
                                    e.printStackTrace();
                                }

                                photoPath = tmpFile.getPath();
                            }

                        }

                    }而(dataCursor.moveToNext());

                    字符串的详细信息=;

                    //串联各种信息单串
                    如果(HOMEPHONE =空&安培;!&安培;!homePhone.equals())
                        细节=家庭电话:+ HOMEPHONE +\ N的;
                    如果(MOBILEPHONE =空&安培;!&安培;!mobilePhone.equals())
                        细节+ =MOBILEPHONE:+ MOBILEPHONE +\ N的;
                    如果(办公电话=空&安培;!&安培;!workPhone.equals())
                        细节+ =办公电话:+办公电话+\ N的;
                    如果(昵称= NULL和放大器;!&安培;!nickName.equals())
                        细节+ =的绰号:+绰号+\ N的;

                    如果(标题= NULL和放大器;!&安培;!title.equals())
                        细节+ =标题:+标题+\ N的;

                    //添加ID,显示名称,路径,照片和其他细节光标
                    mMatrixCursor.addRow(新对象[] {Long.toString(的ContactID),显示名,photoPath,细节});

                }

            }而(contactsCursor.moveToNext());

        }
        返回mMatrixCursor;
    }

    @覆盖
    保护无效onPostExecute(光标结果){
        //设置包含联系人列表视图光标
        mAdapter.swapCursor(结果);
    }
}

@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    。getMenuInflater()膨胀(R.menu.activity_main,菜单);
    返回true;
}
 

}

  

Detail.java

 公共类的细节延伸活动{
受保护的静态最终诠释CAPTURE_NEW_PICTURE = 1;
ImageView的照片1;
按钮的摄像头,galary,保存;
乌里selectedImageUri;
  字符串selectedPath;
  位图图片;
  私有静态最终诠释CAMERA_REQUEST = 1888;
  公共静态最后弦乐MIMETYPE_FORMALITY =vnd.android.cursor.item / useformality;




  公共静态最终诠释MEDIA_TYPE_IMAGE = 1;
  公共无效的onCreate(包savedInstanceState)
  {
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.custom_list);

        照片1 =(ImageView的)findViewById(R.id.photo);
        摄像头=(按钮)findViewById(R.id.camera);
        galary =(按钮)findViewById(R.id.galary);
        节省=(按钮)findViewById(R.id.save);


        //摄像机图像
        camera.setOnClickListener(新View.OnClickListener()
        {

            @覆盖
            公共无效的onClick(视图v){
                意图cameraIntent =新的意图(android.provider.MediaStore.ACTION_IM​​AGE_CAPTURE);
                startActivityForResult(cameraIntent,CAMERA_REQUEST);
            }
        });

        //图库图片
        galary.setOnClickListener(新View.OnClickListener()
        {

            @覆盖
            公共无效的onClick(视图v){
                意图photoPickerIntent =新的意图(Intent.ACTION_GET_CONTENT);
                photoPickerIntent.setType(图像/ *);
                startActivityForResult(photoPickerIntent,1);
            }
        });

        save.setOnClickListener(新View.OnClickListener()
        {

            @覆盖
            公共无效的onClick(查看arg0中)
            {
                // TODO自动生成方法存根
                 上下文的背景下= getApplicationContext();
                 位图图标= BitmapFactory.de codeResource(context.getResources(),R.id.photo);
                 尝试
                 {
                     意图myIntent =新意图();
                     myIntent.setAction(Intent.ACTION_ATTACH_DATA);
                     myIntent.setType(为image / jpeg);
                     myIntent.putExtra(Intent.EXTRA_STREAM,图标);
                     startActivity(myIntent);

                 }
                 赶上(ActivityNotFoundException E)
                 {
                     e.printStackTrace();

                 }
            }
            });




    }



    保护无效onActivityResult(INT申请code,INT结果code,意图数据){

        如果(要求code == CAMERA_REQUEST和放大器;&安培;结果code == RESULT_OK){

            。位图照片=(位图)data.getExtras()获得(数据);
            photo1.setImageBitmap(照片);
        }
        其他
        {
            如果(数据= NULL和放大器;!&安培;结果code == RESULT_OK)
            {

                  乌里selectedImage = data.getData();

                  的String [] filePathColumn = {MediaStore.Images.Media.DATA};
                  光标光标= getContentResolver()查询(selectedImage,filePathColumn,NULL,NULL,NULL);
                  cursor.moveToFirst();
                  INT参数:columnIndex = cursor.getColumnIndex(filePathColumn [0]);
                  字符串文件路径= cursor.getString(参数:columnIndex);
                  cursor.close();

                  如果(照片= NULL和放大器;!&安培;!photo.isRecycled())
                  {
                      照片= NULL;
                  }

                  照片= BitmapFactory.de codeFILE(文件路径);
                  photo1.setBackgroundResource(0);
                  photo1.setImageBitmap(照片);
            }
            其他
            {
                Log.d(状态:Photopicker取消);
            }

    }
}
 

}

解决方案

试试这个code ......它会完全工作...

这是你的Java类

 公共类演示扩展活动
{
SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor;
点阵位图;
@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    //从联系人内容提供商的联系人存储在此游标
    mMatrixCursor =新MatrixCursor(新的String [] {_id,姓名,照片,细节}​​);

    //适配器在列表视图设置数据
    mAdapter =新SimpleCursorAdapter(getBaseContext()
            R.layout.second,
            空值,
            新的String [] {姓名,照片,详细信息},
            新INT [] {R.id.textView1,R.id.imageView1,R.id.textView2},0);

    //获取引用列表视图
    ListView控件lstContacts =(ListView控件)findViewById(R.id.listView1);

    //设置适配器列表视图
    lstContacts.setAdapter(mAdapter);

    //创建一个AsyncTask的对象来检索和加载列表视图与联系人
    ListViewContactsLoader listViewContactsLoader =新ListViewContactsLoader();

    //启动AsyncTask的过程来检索和加载列表视图与联系人
    listViewContactsLoader.execute();
    lstContacts.setOnItemClickListener(新OnItemClickListener()
    {
        @燮pressWarnings({空,未使用})
        @覆盖
        公共无效onItemClick(适配器视图<>母公司视图中查看,INT位置,长ID)
        {
            ByteArrayOutputStream流=新ByteArrayOutputStream();

            // bitmap.com preSS(Bitmap.Com pressFormat.PNG,100,流);
            字节[]的字节数组= stream.toByteArray();

            意向意图=新的意图(demo.this,secondactivity.class);

            //意向意图=新的意图(Current.this,Next.class);
            intent.putExtra(BMP,字节); //图像
            // intent.putExtra(文字,文本); //文本
            startActivity(意向);
            // startActivity(意向);



        }
    });


}

/ **一个AsyncTask的类来检索和加载列表视图与联系人* /
私有类ListViewContactsLoader扩展的AsyncTask<虚空,虚空,光标> {

    @覆盖
    受保护的光标doInBackground(空... PARAMS){
        乌里contactsUri = ContactsContract.Contacts.CONTENT_URI;

        //查询表ContactsContract.Contacts检索所有联系人
        光标contactsCursor = getContentResolver()查询(contactsUri,NULL,NULL,NULL,
                ContactsContract.Contacts.DISPLAY_NAME +ASC);

        如果(contactsCursor.moveToFirst()){
            做{
                长的ContactID = contactsCursor.getLong(contactsCursor.getColumnIndex(_ ID));


                乌里dataUri = ContactsContract.Data.CONTENT_URI;

                //查询表ContactsContract.Data检索像单个项目
                //家庭电话,移动电话,工作电子邮件等对应于各接触
                光标dataCursor = getContentResolver()查询(dataUri,空,
                        ContactsContract.Data.CONTACT_ID +=+的ContactID,
                        NULL,NULL);



                字符串显示名=;
                字符串nickname =;
                字符串HOMEPHONE =;
                字符串MOBILEPHONE =;
                字符串办公电话=;
                串photoPath =+ R.drawable.ic_launcher;
                byte []的photoByte = NULL;

                字符串标题=;



                如果(dataCursor.moveToFirst()){
                    //获取显示名称
                    显示名= dataCursor.getString(da​​taCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
                    做{

                        //获取昵称
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
                            绰号= dataCursor.getString(da​​taCursor.getColumnIndex(数据1));

                        //获取电话号码
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
                            开关(dataCursor.getInt(dataCursor.getColumnIndex(数据2))){
                            案例ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
                                HOMEPHONE = dataCursor.getString(da​​taCursor.getColumnIndex(数据1));
                                打破;
                            案例ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
                                MOBILEPHONE = dataCursor.getString(da​​taCursor.getColumnIndex(数据1));
                                打破;
                            案例ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
                                办公电话= dataCursor.getString(da​​taCursor.getColumnIndex(数据1));
                                打破;
                            }
                        }





                        //获取照片
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){
                            photoByte = dataCursor.getBlob(dataCursor.getColumnIndex(DATA15));

                            如果(photoByte!= NULL){
                                位= BitmapFactory.de codeByteArray(photoByte,0,photoByte.length);

                                //获取缓存目录
                                文件cacheDirectory = getBaseContext()getCacheDir()。

                                //临时文件来存储接触式图像
                                文件TMPFILE =新的文件(cacheDirectory.getPath()+/wpta_"+contactId+".png);

                                //然后,FileOutputStream临时文件
                                尝试 {
                                    FileOutputStream中fOutStream =新的FileOutputStream(TMPFILE);

                                    //编写位图到临时文件作为PNG文件
                                    bitmap.com preSS(Bitmap.Com pressFormat.PNG,100,fOutStream);

                                    //刷新的FileOutputStream
                                    fOutStream.flush();

                                    //关闭的FileOutputStream
                                    fOutStream.close();

                                }赶上(例外五){
                                    e.printStackTrace();
                                }

                                photoPath = tmpFile.getPath();
                            }

                        }

                    }而(dataCursor.moveToNext());

                    字符串的详细信息=;

                    //串联各种信息单串
                    如果(HOMEPHONE =空&安培;!&安培;!homePhone.equals())
                        细节=家庭电话:+ HOMEPHONE +\ N的;
                    如果(MOBILEPHONE =空&安培;!&安培;!mobilePhone.equals())
                        细节+ =MOBILEPHONE:+ MOBILEPHONE +\ N的;
                    如果(办公电话=空&安培;!&安培;!workPhone.equals())
                        细节+ =办公电话:+办公电话+\ N的;
                    如果(昵称= NULL和放大器;!&安培;!nickName.equals())
                        细节+ =的绰号:+绰号+\ N的;

                    如果(标题= NULL和放大器;!&安培;!title.equals())
                        细节+ =标题:+标题+\ N的;

                    //添加ID,显示名称,路径,照片和其他细节光标
                    mMatrixCursor.addRow(新对象[] {Long.toString(的ContactID),显示名,photoPath,细节});

                }

            }而(contactsCursor.moveToNext());

        }
        返回mMatrixCursor;
    }

    @覆盖
    保护无效onPostExecute(光标结果){
        //设置包含联系人列表视图光标
        mAdapter.swapCursor(结果);
    }
}

 }
 

这是你的ListView布局

listview.xml

 < RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
机器人:layout_width =FILL_PARENT
机器人:layout_height =FILL_PARENT>

<的ListView
    机器人:ID =@ + ID / ListView1的
    机器人:layout_width =match_parent
    机器人:layout_height =WRAP_CONTENT
    机器人:layout_alignParentLeft =真
    机器人:layout_alignParentTop =真正的>
< / ListView控件>

  < / RelativeLayout的>
 

这里是你的项目布局,只需用你的名字更改

 < XML版本=1.0编码=UTF-8&GT?;
 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:方向=垂直>

<的TextView
    机器人:ID =@ + ID / textView1
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:文本=TextView的/>

< ImageView的
    机器人:ID =@ + ID / imageView1
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:SRC =@可绘制/ ic_launcher/>

<的TextView
    机器人:ID =@ + ID / textView2
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    机器人:文本=TextView的/>

  < / LinearLayout中>
 

和把这个权限在你的maniefest文件。

 <使用-SDK
     安卓的minSdkVersion =8
    机器人:targetSdkVersion =18/>

<使用-权限的Andr​​oid:名称=android.permission.READ_EXTERNAL_STORAG​​E/>
<使用-权限的Andr​​oid:名称=android.permission.WRITE_EXTERNAL_STORAG​​E/>
<使用-权限的Andr​​oid:名称=android.permission.READ_CONTACTS/>
 

下面是第二类

 公共类secondactivity延伸活动{
受保护的静态最终诠释CAPTURE_NEW_PICTURE = 1;
ImageView的照片1;
按钮的摄像头,galary,保存;
乌里selectedImageUri;
字符串selectedPath;
位图图片;
私有静态最终诠释CAMERA_REQUEST = 1888;
公共静态最后弦乐MIMETYPE_FORMALITY =vnd.android.cursor.item / useformality;




公共静态最终诠释MEDIA_TYPE_IMAGE = 1;
公共无效的onCreate(包savedInstanceState)
{
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);

    照片1 =(ImageView的)findViewById(R.id.imageView1);
    摄像头=(按钮)findViewById(R.id.button1);
    galary =(按钮)findViewById(R.id.button2);
    节省=(按钮)findViewById(R.id.button3);


    //摄像机图像
    camera.setOnClickListener(新View.OnClickListener()
    {

        @覆盖
        公共无效的onClick(视图v){
            意图cameraIntent =新的意图(android.provider.MediaStore.ACTION_IM​​AGE_CAPTURE);
            startActivityForResult(cameraIntent,CAMERA_REQUEST);
        }
    });

    //图库图片
    galary.setOnClickListener(新View.OnClickListener()
    {

        @覆盖
        公共无效的onClick(视图v){
            意图photoPickerIntent =新的意图(Intent.ACTION_GET_CONTENT);
            photoPickerIntent.setType(图像/ *);
            startActivityForResult(photoPickerIntent,1);
        }
    });

    save.setOnClickListener(新View.OnClickListener()
    {

        @覆盖
        公共无效的onClick(查看arg0中)
        {
            // TODO自动生成方法存根
            上下文的背景下= getApplicationContext();
            位图图标= BitmapFactory.de codeResource(context.getResources(),R.id.imageView1);
            尝试
            {
                意图myIntent =新意图();
                myIntent.setAction(Intent.ACTION_ATTACH_DATA);
                myIntent.setType(为image / jpeg);
                myIntent.putExtra(Intent.EXTRA_STREAM,图标);
                startActivity(myIntent);

            }
            赶上(ActivityNotFoundException E)
            {
                e.printStackTrace();

            }
        }
    });




}



保护无效onActivityResult(INT申请code,INT结果code,意图数据){

    如果(要求code == CAMERA_REQUEST和放大器;&安培;结果code == RESULT_OK){

        。位图照片=(位图)data.getExtras()获得(数据);
        photo1.setImageBitmap(照片);
    }
    其他
    {
        如果(数据= NULL和放大器;!&安培;结果code == RESULT_OK)
        {

            乌里selectedImage = data.getData();

            的String [] filePathColumn = {MediaStore.Images.Media.DATA};
            光标光标= getContentResolver()查询(selectedImage,filePathColumn,NULL,NULL,NULL);
            cursor.moveToFirst();
            INT参数:columnIndex = cursor.getColumnIndex(filePathColumn [0]);
            字符串文件路径= cursor.getString(参数:columnIndex);
            cursor.close();

            如果(照片= NULL和放大器;!&安培;!photo.isRecycled())
            {
                照片= NULL;
            }

            照片= BitmapFactory.de codeFILE(文件路径);
            photo1.setBackgroundResource(0);
            photo1.setImageBitmap(照片);
        }
        其他
        {
            Log.d(状态:Photopicker取消);
        }

    }
}
  }
 

in main activity display list of contact. now select any contact and open Detail.java Activity. now i want to set this particular selected contact image from second activity imageview. mainActivity.java

public class MainActivity extends Activity {

SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor; 
Bitmap bitmap;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // The contacts from the contacts content provider is stored in this cursor
    mMatrixCursor = new MatrixCursor(new String[] { "_id","name","photo","details"} );

    // Adapter to set data in the listview
    mAdapter = new SimpleCursorAdapter(getBaseContext(),
            R.layout.lv_layout,
            null,
            new String[] { "name","photo","details"},
            new int[] { R.id.tv_name,R.id.iv_photo,R.id.tv_details}, 0);

    // Getting reference to listview
    ListView lstContacts = (ListView) findViewById(R.id.lst_contacts);

    // Setting the adapter to listview
    lstContacts.setAdapter(mAdapter);        

    // Creating an AsyncTask object to retrieve and load listview with contacts
    ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();

    // Starting the AsyncTask process to retrieve and load listview with contacts
    listViewContactsLoader.execute();   
    lstContacts.setOnItemClickListener(new OnItemClickListener() 
    {
          @SuppressWarnings({ "null", "unused" })
        @Override 
          public void onItemClick(AdapterView<?> parent, View view,int position, long id)
          {
              ByteArrayOutputStream stream = new ByteArrayOutputStream();

             // bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
              byte[] byteArray = stream.toByteArray();

              Intent intent = new Intent(MainActivity.this, detail.class);

            //  Intent intent = new Intent(Current.this, Next.class);
              intent.putExtra("bmp", byteArray); // for image
            //  intent.putExtra("text", text); //for text 
              startActivity(intent);
            //  startActivity(intent);



          }
    }); 


}    

/** An AsyncTask class to retrieve and load listview with contacts */
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor>{     

    @Override
    protected Cursor doInBackground(Void... params) {
        Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;

        // Querying the table ContactsContract.Contacts to retrieve all the contacts
        Cursor contactsCursor = getContentResolver().query(contactsUri, null, null, null, 
                                ContactsContract.Contacts.DISPLAY_NAME + " ASC ");

        if(contactsCursor.moveToFirst()){
            do{
                long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));


                Uri dataUri = ContactsContract.Data.CONTENT_URI;

                // Querying the table ContactsContract.Data to retrieve individual items like
                // home phone, mobile phone, work email etc corresponding to each contact 
                Cursor dataCursor = getContentResolver().query(dataUri, null, 
                                        ContactsContract.Data.CONTACT_ID + "=" + contactId, 
                                        null, null);



                String displayName="";
                String nickName="";
                String homePhone="";
                String mobilePhone="";
                String workPhone="";
                String photoPath="" + R.drawable.blank;
                byte[] photoByte=null;

                String title="";



                if(dataCursor.moveToFirst()){
                    // Getting Display Name
                    displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
                    do{

                        // Getting NickName
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
                            nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));

                        // Getting Phone numbers
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
                            switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
                                case ContactsContract.CommonDataKinds.Phone.TYPE_HOME : 
                                    homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                    break;
                                case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE : 
                                    mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                    break;
                                case ContactsContract.CommonDataKinds.Phone.TYPE_WORK : 
                                    workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                    break;  
                            }
                        }





                        // Getting Photo    
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){                               
                            photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));

                            if(photoByte != null) {                         
                                 bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);

                                // Getting Caching directory 
                                File cacheDirectory = getBaseContext().getCacheDir();

                                // Temporary file to store the contact image 
                                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+contactId+".png");

                                // The FileOutputStream to the temporary file
                                try {
                                    FileOutputStream fOutStream = new FileOutputStream(tmpFile);

                                    // Writing the bitmap to the temporary file as png file
                                    bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

                                    // Flush the FileOutputStream
                                    fOutStream.flush();

                                    //Close the FileOutputStream
                                    fOutStream.close();

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                photoPath = tmpFile.getPath();
                            }

                        }

                    }while(dataCursor.moveToNext());                    

                    String details = "";

                    // Concatenating various information to single string
                    if(homePhone != null && !homePhone.equals("") )
                        details = "HomePhone : " + homePhone + "\n";
                    if(mobilePhone != null && !mobilePhone.equals("") )
                        details += "MobilePhone : " + mobilePhone + "\n";
                    if(workPhone != null && !workPhone.equals("") )
                        details += "WorkPhone : " + workPhone + "\n";
                    if(nickName != null && !nickName.equals("") )
                        details += "NickName : " + nickName + "\n";

                    if(title != null && !title.equals("") )
                        details += "Title : " + title + "\n";

                    // Adding id, display name, path to photo and other details to cursor
                    mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,photoPath,details});

                }

            }while(contactsCursor.moveToNext());

        }
        return mMatrixCursor;
    }

    @Override
    protected void onPostExecute(Cursor result) {           
        // Setting the cursor containing contacts to listview
        mAdapter.swapCursor(result);
    }       
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

Detail.java

public class detail extends Activity{
protected static final int CAPTURE_NEW_PICTURE = 1;
ImageView photo1;
Button camera, galary,save;
Uri selectedImageUri;
  String  selectedPath;
  Bitmap photo;
  private static final int CAMERA_REQUEST = 1888; 
  public static final String MIMETYPE_FORMALITY = "vnd.android.cursor.item/useformality";




  public static final int MEDIA_TYPE_IMAGE = 1;
  public void onCreate(Bundle savedInstanceState)
  {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_list);

        photo1=(ImageView)findViewById(R.id.photo);
        camera=(Button)findViewById(R.id.camera);
        galary=(Button)findViewById(R.id.galary);
        save=(Button)findViewById(R.id.save);


        //camera picture 
        camera.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                startActivityForResult(cameraIntent, CAMERA_REQUEST); 
            }
        });

        //gallery picture
        galary.setOnClickListener(new View.OnClickListener() 
        {

            @Override
            public void onClick(View v) {
                Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
                photoPickerIntent.setType("image/*");
                startActivityForResult(photoPickerIntent, 1);
            }
        });

        save.setOnClickListener(new View.OnClickListener() 
        {

            @Override
            public void onClick(View arg0)
            {
                // TODO Auto-generated method stub
                 Context context= getApplicationContext();
                 Bitmap icon= BitmapFactory.decodeResource(context.getResources(), R.id.photo);
                 try 
                 {  
                     Intent myIntent = new Intent();        
                     myIntent.setAction(Intent.ACTION_ATTACH_DATA); 
                     myIntent.setType("image/jpeg"); 
                     myIntent.putExtra(Intent.EXTRA_STREAM, icon);
                     startActivity(myIntent); 

                 } 
                 catch (ActivityNotFoundException e)
                 {  
                     e.printStackTrace();

                 }
            }
            });




    }



    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  

        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  

            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            photo1.setImageBitmap(photo);
        }
        else 
        {
            if (data != null && resultCode == RESULT_OK) 
            {              

                  Uri selectedImage = data.getData();

                  String[] filePathColumn = {MediaStore.Images.Media.DATA};
                  Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                  cursor.moveToFirst();
                  int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                  String filePath = cursor.getString(columnIndex);
                  cursor.close();

                  if(photo != null && !photo.isRecycled())
                  {
                      photo = null;                
                  }

                  photo = BitmapFactory.decodeFile(filePath);
                  photo1.setBackgroundResource(0);
                  photo1.setImageBitmap(photo);              
            }
            else 
            {
                Log.d("Status:", "Photopicker canceled");            
            }

    } 
}

}

解决方案

try this code...it will perfectly work...

here is your java class

 public class demo  extends Activity
{
SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor; 
Bitmap bitmap;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // The contacts from the contacts content provider is stored in this cursor
    mMatrixCursor = new MatrixCursor(new String[] { "_id","name","photo","details"} );

    // Adapter to set data in the listview
    mAdapter = new SimpleCursorAdapter(getBaseContext(),
            R.layout.second,
            null,
            new String[] { "name","photo","details"},
            new int[] { R.id.textView1,R.id.imageView1,R.id.textView2}, 0);

    // Getting reference to listview
    ListView lstContacts = (ListView) findViewById(R.id.listView1);

    // Setting the adapter to listview
    lstContacts.setAdapter(mAdapter);        

    // Creating an AsyncTask object to retrieve and load listview with contacts
    ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();

    // Starting the AsyncTask process to retrieve and load listview with contacts
    listViewContactsLoader.execute();   
    lstContacts.setOnItemClickListener(new OnItemClickListener() 
    {
        @SuppressWarnings({ "null", "unused" })
        @Override 
        public void onItemClick(AdapterView<?> parent, View view,int position, long id)
        {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            // bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            Intent intent = new Intent(demo.this, secondactivity.class);

            //  Intent intent = new Intent(Current.this, Next.class);
            intent.putExtra("bmp", byteArray); // for image
            //  intent.putExtra("text", text); //for text 
            startActivity(intent);
            //  startActivity(intent);



        }
    }); 


}    

/** An AsyncTask class to retrieve and load listview with contacts */
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor>{     

    @Override
    protected Cursor doInBackground(Void... params) {
        Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;

        // Querying the table ContactsContract.Contacts to retrieve all the contacts
        Cursor contactsCursor = getContentResolver().query(contactsUri, null, null, null, 
                ContactsContract.Contacts.DISPLAY_NAME + " ASC ");

        if(contactsCursor.moveToFirst()){
            do{
                long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));


                Uri dataUri = ContactsContract.Data.CONTENT_URI;

                // Querying the table ContactsContract.Data to retrieve individual items like
                // home phone, mobile phone, work email etc corresponding to each contact 
                Cursor dataCursor = getContentResolver().query(dataUri, null, 
                        ContactsContract.Data.CONTACT_ID + "=" + contactId, 
                        null, null);



                String displayName="";
                String nickName="";
                String homePhone="";
                String mobilePhone="";
                String workPhone="";
                String photoPath="" + R.drawable.ic_launcher;
                byte[] photoByte=null;

                String title="";



                if(dataCursor.moveToFirst()){
                    // Getting Display Name
                    displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
                    do{

                        // Getting NickName
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
                            nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));

                        // Getting Phone numbers
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
                            switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
                            case ContactsContract.CommonDataKinds.Phone.TYPE_HOME : 
                                homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                break;
                            case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE : 
                                mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                break;
                            case ContactsContract.CommonDataKinds.Phone.TYPE_WORK : 
                                workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                break;  
                            }
                        }





                        // Getting Photo    
                        if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){                               
                            photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));

                            if(photoByte != null) {                         
                                bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);

                                // Getting Caching directory 
                                File cacheDirectory = getBaseContext().getCacheDir();

                                // Temporary file to store the contact image 
                                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+contactId+".png");

                                // The FileOutputStream to the temporary file
                                try {
                                    FileOutputStream fOutStream = new FileOutputStream(tmpFile);

                                    // Writing the bitmap to the temporary file as png file
                                    bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

                                    // Flush the FileOutputStream
                                    fOutStream.flush();

                                    //Close the FileOutputStream
                                    fOutStream.close();

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                photoPath = tmpFile.getPath();
                            }

                        }

                    }while(dataCursor.moveToNext());                    

                    String details = "";

                    // Concatenating various information to single string
                    if(homePhone != null && !homePhone.equals("") )
                        details = "HomePhone : " + homePhone + "\n";
                    if(mobilePhone != null && !mobilePhone.equals("") )
                        details += "MobilePhone : " + mobilePhone + "\n";
                    if(workPhone != null && !workPhone.equals("") )
                        details += "WorkPhone : " + workPhone + "\n";
                    if(nickName != null && !nickName.equals("") )
                        details += "NickName : " + nickName + "\n";

                    if(title != null && !title.equals("") )
                        details += "Title : " + title + "\n";

                    // Adding id, display name, path to photo and other details to cursor
                    mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,photoPath,details});

                }

            }while(contactsCursor.moveToNext());

        }
        return mMatrixCursor;
    }

    @Override
    protected void onPostExecute(Cursor result) {           
        // Setting the cursor containing contacts to listview
        mAdapter.swapCursor(result);
    }       
}

 }

here is your listview layout

listview.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" >
</ListView>

  </RelativeLayout>

here is your items layout,just change it with your name

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

  </LinearLayout>

and put this permission in your maniefest file.

 <uses-sdk
     android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

here is second class

   public class secondactivity extends Activity {
protected static final int CAPTURE_NEW_PICTURE = 1;
ImageView photo1;
Button camera, galary,save;
Uri selectedImageUri;
String  selectedPath;
Bitmap photo;
private static final int CAMERA_REQUEST = 1888; 
public static final String MIMETYPE_FORMALITY = "vnd.android.cursor.item/useformality";




public static final int MEDIA_TYPE_IMAGE = 1;
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    photo1=(ImageView)findViewById(R.id.imageView1);
    camera=(Button)findViewById(R.id.button1);
    galary=(Button)findViewById(R.id.button2);
    save=(Button)findViewById(R.id.button3);


    //camera picture 
    camera.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
            startActivityForResult(cameraIntent, CAMERA_REQUEST); 
        }
    });

    //gallery picture
    galary.setOnClickListener(new View.OnClickListener() 
    {

        @Override
        public void onClick(View v) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, 1);
        }
    });

    save.setOnClickListener(new View.OnClickListener() 
    {

        @Override
        public void onClick(View arg0)
        {
            // TODO Auto-generated method stub
            Context context= getApplicationContext();
            Bitmap icon= BitmapFactory.decodeResource(context.getResources(), R.id.imageView1);
            try 
            {  
                Intent myIntent = new Intent();        
                myIntent.setAction(Intent.ACTION_ATTACH_DATA); 
                myIntent.setType("image/jpeg"); 
                myIntent.putExtra(Intent.EXTRA_STREAM, icon);
                startActivity(myIntent); 

            } 
            catch (ActivityNotFoundException e)
            {  
                e.printStackTrace();

            }
        }
    });




}



protected void onActivityResult(int requestCode, int resultCode, Intent data) {  

    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  

        Bitmap photo = (Bitmap) data.getExtras().get("data"); 
        photo1.setImageBitmap(photo);
    }
    else 
    {
        if (data != null && resultCode == RESULT_OK) 
        {              

            Uri selectedImage = data.getData();

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();

            if(photo != null && !photo.isRecycled())
            {
                photo = null;                
            }

            photo = BitmapFactory.decodeFile(filePath);
            photo1.setBackgroundResource(0);
            photo1.setImageBitmap(photo);              
        }
        else 
        {
            Log.d("Status:", "Photopicker canceled");            
        }

    } 
}
  }

这篇关于如何从ImageView的按钮点击更改选定的联系人镜像。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆