總網頁瀏覽量

關於我自己

我的相片
人生的必修課是接受無常,人生的選修課是放下執著。

2012年1月24日 星期二

撈出聯絡人資料 ~ 照片 ~ 並換圖 BitmapFactory.decodeByteArray







要讀取聯絡人資料記得Manifest.xml中要加入




Launch這個AP後, 會撈出Device中聯絡人的資料, 列出有人名(ContactsContract.Contacts.DISPLAY_NAME有值)的資料, 並抓出聯絡人圖片, 如果沒設的就顯示

本範例目的在自行更換圖示, 所以用了兩個Activity -> 選擇要換圖的item後 -> open另一個Activity選圖
















換換換~
帶有圖片的Toast



如此我們便可以任意更換聯絡人圖示~不過這個AP並沒有真正寫入資料到ContactsContract.Contacts,也沒有建立資料庫存放, 所以關閉後所有的變更就會不見囉.
















ContactPhotoActivity.java
package com.tsots.GridView_Contact_ChangePhoto;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
  
public class ContactPhotoActivity extends Activity 
{  
 Context context = ContactPhotoActivity.this;
 List total_contact_id= new ArrayList();
 List contact_name= new ArrayList();
 List contact_photo= new ArrayList();
 GridView g1;
 String photoId;  
 String tag = "com.tsots.GridView_Contact_ChangePhoto / ContactPhotoActivity.java";
 int num_contact=0;
 int num_contact_photo=0;
 int contact_id;
 int photo;
 Bitmap photoBitmap;
 Bitmap tmp_photoBitmap;
 Bitmap map; 

 /** Called when the activity is first created. */  
 @Override  
    public void onCreate(Bundle savedInstanceState) 
 {  
  super.onCreate(savedInstanceState);  
  setContentView(R.layout.main);  
  
  g1 = (GridView) findViewById (R.id.gridview1); 
  //陣列內容: 從contact撈出有顯示名稱的資料
  final String[] selectNameColumn = new String[]{
                                          ContactsContract.Contacts._ID, 
                                          ContactsContract.Contacts.DISPLAY_NAME
                                          };
        final Cursor cursor_ContactName = getContentResolver().query(  
                            Contacts.CONTENT_URI,  //要查詢的表格
                            selectNameColumn,      //要回傳的欄位組合
                            null,  
                            null,  
                            null
                             );  
        try
        {
         cursor_ContactName.moveToFirst();                                              
         do
         {                 
          /*****************************聯絡人在被建立時該id***************************************
           * int idColumn = cursor_ContactName.getColumnIndex(ContactsContract.Contacts._ID);
           * String contactId = cursor_ContactName.getString(idColumn);//會丟入59筆資料
           *****************************等於*****************************************************/
          String contactId = cursor_ContactName.getString(0);  //回傳有DISPLAY_NAME的資料,個人Device有59筆        
          
          /*****************************聯絡人姓名***********************************************
           * final int nameColumn = cursor_ContactName.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
           * String contactName = cursor_ContactName.getString(nameColumn);
           *****************************等於*****************************************************/
          String contactName = cursor_ContactName.getString(1);

          try
          {                  
           byte[] photo = getPhoto(contactId);   //只會得到24筆資料
           num_contact++;
                 map = BitmapFactory.decodeByteArray(photo, 0, photo.length); 
                 total_contact_id.add(String.valueOf(contactId));
                 contact_name.add(num_contact + " " + String.valueOf(contactName));                 
                 contact_photo.add(map);
             }
                catch(Exception e)
                {
                 System.out.println("e = "+e); 
                }
            }while(cursor_ContactName.moveToNext());

            Adapter_ContactPhotoActivity adapter = new Adapter_ContactPhotoActivity(
                                  this,   
                                  contact_name,
                                  contact_photo
                         );
            g1.setNumColumns(3);    //每排3筆資料
            g1.setAdapter(adapter); //自訂的Adapter

            /*
             * 加入GridView的點擊事件
             * 記錄user點選的位置到"CONTACT_POSITION", 這個數值是在PhotoSelect.java中選好換圖事件後,
             * 所要對哪個聯絡人欄位變更資訊的依據
             */
            class  ItemClickListener implements OnItemClickListener
            {
             public void onItemClick(AdapterView arg0,//The AdapterView where the click happened   
                   View v,             //The view within the AdapterView that was clicked  
                   int position,       //The position that be clicked  
                   long id             //The row id of the item that was clicked  
                     ) 
             {                  
              Intent intent = new Intent(context, PhotoSelect.class);
              Bundle bundle = new Bundle();
              bundle.putInt("CONTACT_POSITION", position);
              intent.putExtras(bundle);
              Log.i(tag, "select position : "+position);
              Log.i(tag, "select contact_name : "+contact_name.get(position));
              startActivityForResult(intent,0);
             }
            }
            g1.setOnItemClickListener(new ItemClickListener());       
        }
        finally
        {
         cursor_ContactName.close();
        }
 }
 
 /*
  * 這個function負責從聯絡人中撈出有PHOTO_ID的資料, 並以byte[]的型態回傳
  */
 public byte[] getPhoto(String people_id) 
 {
  byte[] contactIcon = null;
  String photo_id = null;
  String selection1 = ContactsContract.Contacts._ID + " = " + people_id; 
  Cursor cur_select_name = getContentResolver().query(
               ContactsContract.Contacts.CONTENT_URI, /*搜尋對象*/
               null, 
               selection1,                            /*條件*/
               null,
               null
              );
  //會丟入59筆資料    
  if (cur_select_name.getCount() > 0) 
  {
   cur_select_name.moveToFirst();
   photo_id = cur_select_name.getString(cur_select_name.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
  }
  String[] projection = new String[] {ContactsContract.Data.DATA15}; 
  String select_photo = ContactsContract.Data._ID + " = " + photo_id;  //只抓有photo的data
  //String selection = ContactsContract.Data._ID;  //抓所有有名字的data, 且沒有抓到photo值

  Cursor cur_select_photo = getContentResolver().query(
                 ContactsContract.Data.CONTENT_URI, //要查詢的表格        
                 projection,                        //要回傳的欄位組合
                 select_photo,                      //符合這個限制資料的才會回傳
                 null,                              //前一個參數的參數
                 null                               //排序
                );
  //會丟入59筆資料    
  cur_select_photo.moveToFirst();
  /*
   * 若由DISPLAY_NAME過濾後的資料裡, 沒有聯絡人圖片的, 統一給一個圖示, 從.png裡抓
   */
  if(cur_select_photo.getCount() == 0)
  {
   //將圖檔轉成Bitmap
   tmp_photoBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.widget_stock_addnewstock_btn_normal);  
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   //將.png的圖檔轉成Bitmap
   tmp_photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);                                                  
   contactIcon = baos.toByteArray();
   return contactIcon;
  }
  else
  {
   //只會得到24筆資料
   contactIcon = cur_select_photo.getBlob(0);
   return contactIcon;
  }
 }
 
 /*
  * 從PhotoSelect.java操作完選圖的動作
  * 傳回"CONTACT_POSITION"和"CONTACT_PHOTO"到ContactPhotoActivity.java
  */
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) 
 {
  super.onActivityResult(requestCode, resultCode, data);
  switch(resultCode)
  {
   case RESULT_OK:
    Bundle bundle_from_PhotoSelect = data.getExtras();
    contact_id = bundle_from_PhotoSelect.getInt("CONTACT_POSITION");
    photo = bundle_from_PhotoSelect.getInt("CONTACT_PHOTO");
    changePhoto(contact_id, photo);
    break;
  }
 }
 
 public void changePhoto(int id, int photo)
 {  
     tmp_photoBitmap = BitmapFactory.decodeResource(getResources(), photo);     //將int轉成Bitmap
  ByteArrayOutputStream baos_from_PhotoSelect = new ByteArrayOutputStream(); //將Bitmap轉成ByteArrayOutStream
  tmp_photoBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos_from_PhotoSelect);                                                  
  byte[] byte_from_PhotoSelect = baos_from_PhotoSelect.toByteArray();        //將ByteArrayOutStream轉成byte
        map = BitmapFactory.decodeByteArray(byte_from_PhotoSelect, 0, byte_from_PhotoSelect.length);//將byte轉成Bitmap
     contact_photo.set(id, map);    //可以改變contact_photo
     //contact_name.set(id, "xxx"); //可以改變contact_name   
     
        Adapter_ContactPhotoActivity adapter = new Adapter_ContactPhotoActivity(
                                 this,   
                                 contact_name,
                                 contact_photo
                        );
        g1.setNumColumns(3);    //每排3筆資料
        g1.setAdapter(adapter); //自訂的Adapter
 }
 } //



PhotoSelect.java
package com.tsots.GridView_Contact_ChangePhoto;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class PhotoSelect extends Activity
{
 Context context = PhotoSelect.this;
 Adapter_PhotoSelect adapter = new Adapter_PhotoSelect(this);
 Intent intent;
 Bundle bundle;
 int contact_id;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //取得從ContactPhotoActivity.java intent來的bundle資料
        intent=this.getIntent();
        bundle = intent.getExtras();
        contact_id = bundle.getInt("CONTACT_POSITION");
        
        GridView gridview = (GridView) findViewById(R.id.gridview1);
        gridview.setNumColumns(3);
        gridview.setAdapter(adapter);

        gridview.setOnItemClickListener(new OnItemClickListener() 
        {
            public void onItemClick(AdapterView parent, final View v, final int position, final long id) 
            {            
             ImageView iv = new ImageView(context);
             iv.setImageResource(adapter.mThumbIds[position]);
             /*
              * 建立一個AlertDialog, 除了預覽選到的圖片外
              * PositiveButton會傳回"CONTACT_PHOTO","CONTACT_POSITION"的值到前一個畫面
              * NegativeButton則退出AlertDialog
              */
             new AlertDialog.Builder(context)
          .setTitle(getResources().getString(R.string.alertdialog_title))
          .setView(iv)
          .setPositiveButton(getResources().getString(R.string.alertdialog_PositiveButton),
    new DialogInterface.OnClickListener()
    {
     public void onClick(DialogInterface dialog, int which)
     {
      toastWithPhoto(position, v);
      bundle.putInt("CONTACT_PHOTO", adapter.mThumbIds[position]);
      bundle.putInt("CONTACT_POSITION", contact_id);
      intent.putExtras(bundle);
      //以RESULT_OK標籤識別換圖的動作成不成立
      PhotoSelect.this.setResult(RESULT_OK, intent);
      //結束此Activity
      PhotoSelect.this.finish();
     }
    })
    .setNegativeButton(getResources().getString(R.string.alertdialog_NegativeButton), 
    new DialogInterface.OnClickListener()
    {
     public void onClick(DialogInterface dialog, int which)
     {
      
     }
    })
    .show();       
            }
        });
    }
    
    public void toastWithPhoto(int position, View v)
    {
     ImageView iv = new ImageView(context);
     photoChangeSize(position, iv);
     TextView tv = new TextView(context);
     tv.setText(String.valueOf(position));
     LinearLayout lay = new LinearLayout(context);
     lay.setOrientation(LinearLayout.HORIZONTAL);
     Toast toast = Toast.makeText(context, getResources().getString(R.string.toast_text) + tv.getText(), Toast.LENGTH_SHORT);
     View view = toast.getView();
     lay.addView(view);  
     lay.addView(iv);         
     toast.setView(lay);    
     toast.show();
    }
    
    public void photoChangeSize(int position, ImageView iv)
    {
     Matrix matrix = new Matrix();
     float scaleWidth = (float) 0.5;
     float scaleHeigh = (float) 0.5;
     matrix.postScale(scaleWidth, scaleHeigh);
     Bitmap bmp = BitmapFactory.decodeResource(getResources(), adapter.mThumbIds[position]);
     int bmpWidth = bmp.getWidth();
     int bmpHeigh = bmp.getHeight();
     Bitmap resizebmp = Bitmap.createBitmap(bmp,0,0, bmpWidth, bmpHeigh, matrix, true);
     iv.setImageBitmap(resizebmp);
    }
}

ContactPhotoActivity.java的Adapter, 設定GridView的型態是一個ImageView加一個TextView

Adapter_ContactPhotoActivity.java
package com.tsots.GridView_Contact_ChangePhoto;

import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class Adapter_ContactPhotoActivity extends BaseAdapter 
{ 
 private Context photoadapter;
 List _contact_name;
 List _contact_photo;
 String tag = "com.tsots.GridView_Contact_ChangePhoto / Adapter_ContactPhotoActivity.java";  

 public Adapter_ContactPhotoActivity(Context con,List contact_name, List contact_photo) 
 {
  photoadapter = con;
  _contact_name = contact_name;
  _contact_photo = contact_photo;
 }

 public int getCount()
 {
  //return _items.length;
  return _contact_name.size();
 }

 public Object getItem(int position)
 {
  return _contact_name.get(position);
 }

 public long getItemId(int position)
 {
  return position;
 }

 /*
  * 從layout contactactivity_adapter.xml中定義一個TextView與一個ImageView欄位來放置聯絡人圖片與名稱
  */

 public View getView(int position, View convertView, ViewGroup parent)
 {
     LayoutInflater factory = LayoutInflater.from(photoadapter);
     View v = (View) factory.inflate(R.layout.adapter_contactphotoactivity, null);
     TextView tv = (TextView) v.findViewById(R.id.ItemText);
     ImageView iv = (ImageView) v.findViewById(R.id.ItemImage);
     tv.setText(_contact_name.get(position).toString());     

     try
     {
      iv.setImageBitmap(_contact_photo.get(position));
     }
     catch(Exception e)
     {
      Log.e(tag, String.valueOf(e));
     }    
     return v;
 } 
} 

PhotoSelect.java的Adapter, 設定GridView的型態是一個ImageView

Adapter_PhotoSelect.java
package com.tsots.GridView_Contact_ChangePhoto;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class Adapter_PhotoSelect extends BaseAdapter 
{
    private Context mContext;

    public Adapter_PhotoSelect(Context c) 
    {
        mContext = c;
    }

    public int getCount() 
    {
        return mThumbIds.length;
    }

    public Object getItem(int position) 
    {
        return null;
    }

    public long getItemId(int position) 
    {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) 
    {
        ImageView imageView;
        if (convertView == null) 
        {  
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(110, 110));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } 
        else 
        {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

    public Integer[] mThumbIds = 
    {
      R.drawable.pic_01, R.drawable.pic_02,
            R.drawable.pic_03, R.drawable.pic_04,
            R.drawable.pic_05, R.drawable.pic_06,
            R.drawable.pic_07, R.drawable.pic_08,
            R.drawable.pic_09, R.drawable.pic_10,
            R.drawable.pic_11, R.drawable.pic_12,
            R.drawable.pic_13, R.drawable.pic_14,
            R.drawable.pic_15, R.drawable.pic_16,
            R.drawable.pic_17, R.drawable.pic_18,
            R.drawable.pic_19, R.drawable.pic_20,
            R.drawable.pic_21, R.drawable.pic_22,
            R.drawable.pic_23, R.drawable.pic_24,
            R.drawable.pic_25, R.drawable.pic_26,
            R.drawable.pic_27, R.drawable.pic_28,
            R.drawable.pic_29, R.drawable.pic_30,
            R.drawable.pic_31, R.drawable.pic_32,
            R.drawable.pic_33, R.drawable.pic_34
    };
}

1 則留言:

  1. 請問有完整檔案借看嗎ˊˋ
    正在學這個 拜託嚕
    gn01672966@gmail.com
    或者放網上下載也可以 感謝您~~

    回覆刪除