如何在imageview按钮上更改选定的联系人图像。

时间:2014-05-24 10:42:28

标签: android performance android-layout android-intent android-fragments

在主要活动显示联系人列表中。现在选择任何联系人并打开Detail.java活动。现在我想从第二个活动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");            
            }

    } 
}

}

1 个答案:

答案 0 :(得分:2)

试试这段代码......它会完美运作......

这是你的java类

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

 }

这是您的列表视图布局

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>

这是您的商品布局,只需使用您的名称进行更改

 <?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>

并将此权限放入您的maniefest文件中。

 <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" />

这是第二类

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

    } 
}
  }