Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone


Android People Contact List, Name, Phone No, Photo Picture, Email and Address

Android People Contact List, Name, Phone No, Photo Picture, Email and Address ถ้าได้เคยใช้ App พวก LINE หรือ What App ที่มีมากับ iPhone หรือ Android จะเห็นว่า Application เหล่านี้จะสามารถดึงรายชื่อ Contact List ที่อยู่ในหลายเลขโทรศัพท์ของเรามาแสดงใน App ของตัวเอง และเราจะเห็นว่าข้อมูลเหล่านี้ OS เองก็ไม่ได้ห่วงหรือห้าม App อื่น ๆ เรียกใช้ และการเรียกใช้งานก็ไม่ได้ยากซับซ้อนอะไรมากมาย แต่ทั้งนี้ขึ้นอยู่กับว่าจะต้องการดึงข้อมูลอะไรออกมาบ้าง เช่น ต้องการ ชื่อ (DISPLAY_NAME), หมายเลขโทรศัพท์(Phone) , รูปภาพที่อยู่ใน Contact (Photo) หรือข้อมูลอื่น ๆ

Android People Contact List

Android People Contact List


จากภาพจะเห็นว่าเราสามารถเขียน Android เพื่อดึงข้อมูลจาก People Contact List ได้ทั้งที่เป็น ชื่อ(DISPLAY_NAME), หมายเลขโทรศัพท์(Phone) และ รูปภาพ(Photo)

หน้าจอ Contact People บน Android

Android People Contact List

เข้าได้จาก Icons ว่า People

Android People Contact List

เป็นรายชื่อ Contact ที่อยู่ใน Smartphone

Android People Contact List

รายละเอียดของ Contact ในตัวอย่างจะเห็นว่าภายใน 1 Contact จะสามารถมีข้อมูลได้หลายรายการ เช่น หมายเลขโทรศัพท์หลายเบอร์ หรือ อีเมล์หลายตัว

ในการเขียนโปรแกรมเพื่อดึง Contact List ที่อยู่ใน Smartphone นั้นจะต้องกำหนด Permission ที่ไฟล์ AndroidManifest.xml ด้วย

สำหรับขั้นตอนในการดึง Contact List ถ้าเป็นแค่ชื่อที่เป็น DISPLAY_NAME จะสามารถทำได้ง่ายเพียงใช้ Cursor ทำการ Query มาจาก ContactsContract.Contacts ก็จะได้ข้อมูลที่อยู่ในรูปแบบของ Cursor และนำไปใช้ได้ในทันที

1.Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
2.startManagingCursor(cursor);

แต่ถ้าต้องการดึงข้อมูลอื่น ๆ ด้วย เช่น Phone No , Address หรือ Email ซึ่งข้อมูลเหล่านี้ภายใน 1 Contact จะสามารถมีได้หลายรายการ เฉพาะฉะนั้นเมื่อ Loop ข้อมุลในแต่ล่ะ Cursor ก็จะต้องมีการ Loop ข้อมูลของ Phone No ด้วยว่าในแต่ล่ะ Contact มีข้อมูลนั้น ๆ กี่รายการ




และกรณีที่ดึง Photo Contact ก็จะต้องอ่านข้อมูล Photo Contact ที่อยู่ในรุปแบบ Bitmap ก่อนนำมาแสดงผลบน ImageView ด้วย

ในตัวอย่างทั้ง 3 ตัวนี้ ถือได้ว่าเป็นการเลือกข้อมูลที่ค่อนข้างครอบคลุมกับความต้องการใช้งาน ซึ่งยอมรับว่ากว่าจะทำบทความนี้ออกมาได้ก็ใช้เวลาไม่ตำกว่า 5-6 ชม. เพราะข้อมูลบางรายตัวค้นหายาก จะต้องอาสัยการศึกษาจาก Sample Project ที่มากับ Android SDK

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

การกำหนด Permission สำหรับการอ่าน Contact

Android People Contact List

รูปการเพิ่ม Permission บน AndroidManifest.xml


Example 1 การดึงข้อมูลจาก Contact List มาแสดงแบบง่าย ๆ โดยแสดง ID , Name และ Tel

โครงสร้างของไฟล์ประกอบด้วย 2 ไฟล์คือ MainActivity.java, activity_main.xml และ activity_column.xml

Android People Contact List

activity_main.xml
01.<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
02.    android:id="@+id/tableLayout1"
03.    android:layout_width="fill_parent"
04.    android:layout_height="fill_parent">
05.  
06.    <TableRow
07.      android:id="@+id/tableRow1"
08.      android:layout_width="wrap_content"
09.      android:layout_height="wrap_content" >
10.      
11.     <TextView
12.        android:id="@+id/textView1"
13.        android:layout_width="wrap_content"
14.        android:layout_height="wrap_content"
15.        android:gravity="center"
16.        android:text="Contact List : "
17.        android:layout_span="1"
18.        android:textAppearance="?android:attr/textAppearanceLarge" />
19.             
20.    </TableRow>
21. 
22.    <View
23.        android:layout_height="1dip"
24.        android:background="#CCCCCC" />
25.  
26.  <LinearLayout
27.        android:orientation="horizontal"
28.        android:layout_width="fill_parent"
29.        android:layout_height="wrap_content"
30.        android:layout_weight="0.1">  
31.      
32.     <ListView
33.         android:id="@+id/listView1"
34.         android:layout_width="match_parent"
35.         android:layout_height="wrap_content">
36.     </ListView>
37.             
38.    </LinearLayout>
39. 
40.    <View
41.        android:layout_height="1dip"
42.        android:background="#CCCCCC" />
43.           
44.    <LinearLayout
45.      android:id="@+id/LinearLayout1"
46.      android:layout_width="wrap_content"
47.      android:layout_height="wrap_content"
48.      android:padding="5dip" >
49. 
50.        <TextView
51.            android:id="@+id/textView2"
52.            android:layout_width="wrap_content"
53.            android:layout_height="wrap_content"
54.            android:text="By.. ThaiCreate.Com" />
55. 
56.    </LinearLayout>
57.     
58.</TableLayout>

ไฟล์ XML Layout ของ Activity หลัก


Android People Contact List

activity_column.xml
01.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
02.    android:id="@+id/linearLayout1"
03.    android:layout_width="fill_parent"
04.    android:layout_height="fill_parent" >
05. 
06.    <TextView
07.    android:id="@+id/ColID"
08.        android:layout_width="0dp"
09.        android:layout_height="wrap_content"
10.        android:layout_weight="1"
11.        android:text="ID"/>
12. 
13.    <TextView
14.        android:id="@+id/ColName"
15.        android:layout_width="0dp"
16.        android:layout_height="wrap_content"
17.        android:layout_weight="1"
18.        android:text="Name"/>
19. 
20.    <TextView
21.        android:id="@+id/ColPhoneNo"
22.        android:layout_width="0dp"
23.        android:layout_height="wrap_content"
24.        android:layout_weight="1"
25.        android:text="Tel" />
26. 
27.</LinearLayout>

XML Layout ของ Custom Layout ของ ListView

MainActivity.java
001.package com.myapp;
002. 
003.import android.os.Bundle;
004.import android.provider.ContactsContract;
005.import android.view.LayoutInflater;
006.import android.view.Menu;
007.import android.view.View;
008.import android.view.ViewGroup;
009.import android.widget.AdapterView;
010.import android.widget.AdapterView.OnItemClickListener;
011.import android.widget.BaseAdapter;
012.import android.widget.ListView;
013.import android.widget.TextView;
014.import android.widget.Toast;
015.import android.app.Activity;
016.import android.content.Context;
017.import android.database.Cursor;
018. 
019.public class MainActivity extends Activity {
020.       
021.    String arrData[][];
022.     
023.    @Override
024.    public void onCreate(Bundle savedInstanceState) {
025.        super.onCreate(savedInstanceState);
026.        setContentView(R.layout.activity_main);
027. 
028.        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
029.        startManagingCursor(cursor);
030.            
031.    if(cursor != null)
032.    {
033.        if (cursor.moveToFirst()) {
034.            arrData = new String[cursor.getCount()][cursor.getColumnCount()];
035.            /***
036.             *  [x][0] = ID
037.             *  [x][1] = Name
038.             *  [x][2] = PhoneNo
039.             */
040.             
041.            int i= 0;
042.            do { // Start Loop all contact     
043.                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
044.                 
045.                // ID
046.                arrData[i][0] = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
047.                 
048.                // Display Name
049.                arrData[i][1] = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
050.                 
051.                // Phone No
052.                if (Integer.parseInt(cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { // Count of Number
053.                Cursor pCur = getContentResolver().query(
054.                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
055.                        null,
056.                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
057.                        new String[]{id}, null);
058.                        // Loop for Phone No
059.                    while (pCur.moveToNext()) {
060.                        String PhoneNo = pCur.getString( pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
061.                        if(arrData[i][2] != null)
062.                        {
063.                            arrData[i][2] = arrData[i][2] + ", " + PhoneNo;
064.                        }
065.                        else
066.                        {
067.                            arrData[i][2] = PhoneNo;
068.                        }
069.                    }
070.                    pCur.close();
071.                 
072.                }
073.                 
074.                i++;
075.            } while (cursor.moveToNext());                     
076. 
077.        }
078.    }
079.    cursor.close();
080.         
081.        final ListView lView1 = (ListView)findViewById(R.id.listView1);
082.        lView1.setAdapter(new ImageAdapter(this,arrData));
083.         
084.        // OnClick
085.        lView1.setOnItemClickListener(new OnItemClickListener() {
086.            public void onItemClick(AdapterView<?> parent, View v,
087.                int position, long id) {
088.                 
089.                   Toast.makeText(getApplicationContext(),
090.                    "Your selected : " + arrData[position][1].toString(), Toast.LENGTH_SHORT).show();
091.                 
092.            }
093.        });
094.       
095.    }
096. 
097.    public class ImageAdapter extends BaseAdapter
098.    {
099.        private Context context;
100.        private String[][] lis;
101.         
102.        public ImageAdapter(Context c, String[][] li)
103.        {
104.            // TODO Auto-generated method stub
105.            context = c;
106.            lis = li;
107.        }
108.  
109.        public int getCount() {
110.            // TODO Auto-generated method stub
111.            return lis.length;
112.        }
113.  
114.        public Object getItem(int position) {
115.            // TODO Auto-generated method stub
116.            return position;
117.        }
118.  
119.        public long getItemId(int position) {
120.            // TODO Auto-generated method stub
121.            return position;
122.        }
123.  
124.        public View getView(int position, View convertView, ViewGroup parent) {
125.            // TODO Auto-generated method stub
126.             
127.            LayoutInflater inflater = (LayoutInflater) context
128.                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
129.          
130.            if (convertView == null) {
131.                convertView = inflater.inflate(R.layout.activity_column, null);
132.            }
133. 
134. 
135.            // ColID
136.            TextView txtID = (TextView) convertView.findViewById(R.id.ColID);
137.            txtID.setPadding(0, 0, 0, 0);
138.            txtID.setText(lis[position][0].toString());
139. 
140.            // ColName
141.            TextView txtName = (TextView) convertView.findViewById(R.id.ColName);
142.            txtName.setPadding(0, 0, 0, 0);
143.            txtName.setText(lis[position][1].toString());
144.             
145.            // ColPhoneNo
146.            TextView txtPhoneNo = (TextView) convertView.findViewById(R.id.ColPhoneNo);
147.            txtPhoneNo.setText(lis[position][2].toString());
148.  
149.            return convertView;
150. 
151.        }
152.    }
153.     
154.     
155.    @Override
156.    public boolean onCreateOptionsMenu(Menu menu) {
157.        getMenuInflater().inflate(R.menu.activity_main, menu);
158.        return true;
159.    }
160. 
161.}


Screenshot

Android People Contact List

แสดงข้อมูล Contact List โดยมี Display Name และหมายหลขโทรศัพท์



Example 2 การดึง Photo Contact จาก Contact List มาแสดงใน ListView และใช้ ArrayList และ HashMap เข้ามาจัดเก็บข้อมูลเพราะสามารถจัดเก็บได้ทั้งข้อความและ Bitmap ของ Photo Contact

โครงสร้างของไฟล์ประกอบด้วย 2 ไฟล์คือ MainActivity.java, activity_main.xml และ activity_column.xml

Android People Contact List

activity_main.xml
01.<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
02.    android:id="@+id/tableLayout1"
03.    android:layout_width="fill_parent"
04.    android:layout_height="fill_parent">
05.  
06.    <TableRow
07.      android:id="@+id/tableRow1"
08.      android:layout_width="wrap_content"
09.      android:layout_height="wrap_content" >
10.      
11.     <TextView
12.        android:id="@+id/textView1"
13.        android:layout_width="wrap_content"
14.        android:layout_height="wrap_content"
15.        android:gravity="center"
16.        android:text="Contact List : "
17.        android:layout_span="1"
18.        android:textAppearance="?android:attr/textAppearanceLarge" />
19.             
20.    </TableRow>
21. 
22.    <View
23.        android:layout_height="1dip"
24.        android:background="#CCCCCC" />
25.  
26.  <LinearLayout
27.        android:orientation="horizontal"
28.        android:layout_width="fill_parent"
29.        android:layout_height="wrap_content"
30.        android:layout_weight="0.1">  
31.      
32.     <ListView
33.         android:id="@+id/listView1"
34.         android:layout_width="match_parent"
35.         android:layout_height="wrap_content">
36.     </ListView>
37.             
38.    </LinearLayout>
39. 
40.    <View
41.        android:layout_height="1dip"
42.        android:background="#CCCCCC" />
43.           
44.    <LinearLayout
45.      android:id="@+id/LinearLayout1"
46.      android:layout_width="wrap_content"
47.      android:layout_height="wrap_content"
48.      android:padding="5dip" >
49. 
50.        <TextView
51.            android:id="@+id/textView2"
52.            android:layout_width="wrap_content"
53.            android:layout_height="wrap_content"
54.            android:text="By.. ThaiCreate.Com" />
55. 
56.    </LinearLayout>
57.     
58.</TableLayout>

ไฟล์ XML Layout ของ Activity หลัก


Android People Contact List

activity_column.xml
01.<?xml version="1.0" encoding="utf-8"?>
02.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03.    android:orientation="horizontal"
04.    android:layout_width="fill_parent"
05.    android:layout_height="fill_parent">
06.    <ImageView
07.        android:id="@+id/ColPhoto"
08.        android:layout_width="60dp"
09.        android:layout_height="60dp"
10.    />
11.    <LinearLayout
12.        android:orientation="vertical"
13.        android:layout_width="fill_parent"
14.        android:layout_height="fill_parent">
15.        <LinearLayout
16.            android:orientation="horizontal"
17.            android:layout_width="wrap_content"
18.            android:layout_height="wrap_content">
19.            <TextView
20.                android:layout_width="wrap_content"
21.                android:layout_height="wrap_content"
22.                android:text="Name: "
23.            />
24.            <TextView android:id="@+id/ColName"
25.                android:layout_width="wrap_content"
26.                android:layout_height="wrap_content"
27.            />
28.        </LinearLayout>
29.        <LinearLayout
30.            android:orientation="horizontal"
31.            android:layout_width="wrap_content"
32.            android:layout_height="wrap_content">
33.            <TextView
34.                android:layout_width="wrap_content"
35.                android:layout_height="wrap_content"
36.                android:text="No: "
37.            />
38.            <TextView android:id="@+id/ColPhoneNo"
39.                android:layout_width="wrap_content"
40.                android:layout_height="wrap_content"
41.            />
42.        </LinearLayout>
43.    </LinearLayout>
44.</LinearLayout>

ไฟล์ Custom Layout ของ ListView

MainActivity.java
001.package com.myapp;
002. 
003.import java.io.InputStream;
004.import java.util.ArrayList;
005.import java.util.HashMap;
006. 
007.import android.net.Uri;
008.import android.os.Bundle;
009.import android.provider.ContactsContract;
010.import android.view.LayoutInflater;
011.import android.view.Menu;
012.import android.view.View;
013.import android.view.ViewGroup;
014.import android.widget.AdapterView;
015.import android.widget.AdapterView.OnItemClickListener;
016.import android.widget.BaseAdapter;
017.import android.widget.ImageView;
018.import android.widget.ListView;
019.import android.widget.TextView;
020.import android.widget.Toast;
021.import android.app.Activity;
022.import android.content.ContentResolver;
023.import android.content.ContentUris;
024.import android.content.Context;
025.import android.database.Cursor;
026.import android.graphics.Bitmap;
027.import android.graphics.BitmapFactory;
028. 
029.public class MainActivity extends Activity {
030.       
031.    ArrayList<HashMap<String, Object>> MyArrList;
032.     
033.    @Override
034.    public void onCreate(Bundle savedInstanceState) {
035.        super.onCreate(savedInstanceState);
036.        setContentView(R.layout.activity_main);
037. 
038.        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
039.        startManagingCursor(cursor);
040.         
041.        MyArrList = new ArrayList<HashMap<String, Object>>();
042.        HashMap<String, Object> map;
043.            
044.        if(cursor != null)
045.        {
046.            if (cursor.moveToFirst()) {
047.                 
048.                 
049.                map = new HashMap<String, Object>();
050.                /***
051.                 *  ID
052.                 *  NAME
053.                 *  PHONENO
054.                 *  PHOTO
055.                 */
056.                 
057.                do { // Start Loop all contact     
058.                    String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
059.                     
060.                    map = new HashMap<String, Object>();
061.                     
062.                    // ID
063.                    map.put("ID", (String)cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts._ID)));
064.                     
065.                    // Display Name
066.                    map.put("NAME", (String)cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
067.                     
068.                    // Phone No
069.                    String tmpPhoneNo = "";
070.                    if (Integer.parseInt(cursor.getString(cursor.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { // Count of Number
071.                        Cursor pCur = getContentResolver().query(
072.                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
073.                                null,
074.                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
075.                                new String[]{id}, null);
076.                                // Loop for Phone No
077.                                while (pCur.moveToNext()) {
078.                                    String PhoneNo = pCur.getString(pCur.getColumnIndex( ContactsContract.CommonDataKinds.Phone.DATA));
079.                                    if(tmpPhoneNo != null)
080.                                    {
081.                                        tmpPhoneNo = tmpPhoneNo + ", " + PhoneNo;
082.                                    }
083.                                    else
084.                                    {
085.                                        tmpPhoneNo = PhoneNo;
086.                                    }
087.                                }
088.                                pCur.close();
089.                         
090.                    }
091.                     
092.                    // PhoneNo
093.                    map.put("PHONENO", (String)tmpPhoneNo);
094.                     
095.                    // Photo Bitmap
096.                    Bitmap tmpPhoto = null;
097.                    final ContentResolver resolver = getContentResolver();
098.                    Cursor sCur = resolver.query(
099.                            ContactsContract.Data.CONTENT_URI,
100.                            null,
101.                            ContactsContract.Data.CONTACT_ID + "=" + id + " AND "
102.                                    + ContactsContract.Data.MIMETYPE + "='"
103.                                    + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
104.                            null);
105.                    if (sCur == null) {
106.                        tmpPhoto = null;
107.                    }
108.                    else
109.                    {
110.                        Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long
111.                                .parseLong(id));
112.                        InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
113.                         if (input == null) { 
114.                             tmpPhoto = null;
115.                         }
116.                         else
117.                         {
118.                             tmpPhoto= BitmapFactory.decodeStream(input);
119.                         }
120.      
121.                    }
122.                    sCur.close();
123.                    map.put("PHOTO", (Bitmap)tmpPhoto);
124.                     
125.                    // Add to ArrayList
126.                    MyArrList.add(map);
127.             
128.                } while (cursor.moveToNext());                     
129. 
130.            }
131.        }
132.        cursor.close();
133.         
134.        final ListView lView1 = (ListView)findViewById(R.id.listView1);
135.        lView1.setAdapter(new ImageAdapter(this));
136.         
137.        // OnClick
138.        lView1.setOnItemClickListener(new OnItemClickListener() {
139.        public void onItemClick(AdapterView<?> parent, View v,
140.            int position, long id) {
141.             
142.               Toast.makeText(getApplicationContext(),
143.                "Your selected : " + MyArrList.get(position).get("ID"), Toast.LENGTH_SHORT).show();
144.         
145.                //*** for ACTION_CALL
146.               /*
147.                *
148.            Intent intent = new Intent(Intent.ACTION_CALL);
149.            long phoneId =  Integer.parseInt(MyArrList.get(position).get("ID"));
150.            intent.setData(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,  phoneId));
151.            startActivity(intent);
152.             */
153.         
154.        }
155.    });
156.       
157.    }
158. 
159.    public class ImageAdapter extends BaseAdapter
160.    {
161.        private Context context;
162.         
163.        public ImageAdapter(Context c)
164.        {
165.            // TODO Auto-generated method stub
166.            context = c;
167.        }
168.  
169.        public int getCount() {
170.            // TODO Auto-generated method stub
171.            return MyArrList.size();
172.        }
173.  
174.        public Object getItem(int position) {
175.            // TODO Auto-generated method stub
176.            return position;
177.        }
178.  
179.        public long getItemId(int position) {
180.            // TODO Auto-generated method stub
181.            return position;
182.        }
183.  
184.    public View getView(int position, View convertView, ViewGroup parent) {
185.        // TODO Auto-generated method stub
186.         
187.        LayoutInflater inflater = (LayoutInflater) context
188.                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
189.      
190.        if (convertView == null) {
191.            convertView = inflater.inflate(R.layout.activity_column, null);
192.        }
193.      
194.                 
195.        // ColPhoto
196.        ImageView imgPhoto = (ImageView) convertView.findViewById(R.id.ColPhoto);
197.        imgPhoto.setPadding(5, 5, 5, 5);
198.        Bitmap bm = (Bitmap)MyArrList.get(position).get("PHOTO");
199.        if (bm != null) {
200.            imgPhoto.setImageBitmap(bm);
201.        } else {
202.            imgPhoto.setImageResource(android.R.drawable.sym_def_app_icon); // No Photo (Default)
203.        }
204. 
205.        // ColName
206.        TextView txtName = (TextView) convertView.findViewById(R.id.ColName);
207.        txtName.setPadding(10, 0, 0, 0);
208.        txtName.setText(MyArrList.get(position).get("NAME").toString());
209.         
210.        // ColPhoneNo
211.        TextView txtPhoneNo = (TextView) convertView.findViewById(R.id.ColPhoneNo);
212.        txtPhoneNo.setText(MyArrList.get(position).get("PHONENO").toString());
213. 
214.        return convertView;
215. 
216.    }
217.    }
218.     
219.     
220.    @Override
221.    public boolean onCreateOptionsMenu(Menu menu) {
222.        getMenuInflater().inflate(R.menu.activity_main, menu);
223.        return true;
224.    }
225. 
226.}


แสดง Contact List ซึ่งจะดึง Photo Contact มาแสดงใน ListView ด้วย

Screenshot

Android People Contact List




Example 2.1 แสดงรายละเอียดอื่น ๆ เมื่อคลิกที่ Contact แต่ล่ะคนใน ListView

Android People Contact List

ใน Contact ของ Android จะสังเกตุว่าจะมีข้อมูลอื่น ๆ ที่สามารถจัดเก็บได้ด้วย เช่น Email , Address ซึ่งข้อมูลเหล่านี้สามารถมีได้หลายรายการ

MainActivity.java
1.Intent newActivity = new Intent(MainActivity.this,DetailActivity.class);
2.newActivity.putExtra("PhoneID", MyArrList.get(position).get("ID"));
3.startActivity(newActivity);

ใน Event ของ lView1.setOnItemClickListener() ให้แก้ไขเป็นการ Intent มายัง DetailActivity.class

เพิ่มไฟล์ activity_detail.xml และ DetailActivity.java

Android People Contact List

activity_detail.xml
001.<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
002.    android:id="@+id/tableLayout1"
003.    android:layout_width="fill_parent"
004.    android:layout_height="fill_parent">
005.  
006.    <TableRow
007.      android:id="@+id/tableRow1"
008.      android:layout_width="wrap_content"
009.      android:layout_height="wrap_content" >
010.      
011.     <TextView
012.        android:id="@+id/textView1"
013.        android:layout_width="wrap_content"
014.        android:layout_height="wrap_content"
015.        android:gravity="center"
016.        android:text="Contact Detail : "
017.        android:layout_span="1"
018.        android:textAppearance="?android:attr/textAppearanceLarge" />
019. 
020.     <Button
021.         android:id="@+id/btnBack"
022.         android:layout_width="wrap_content"
023.         android:layout_height="wrap_content"
024.         android:text="Back" />
025.             
026.    </TableRow>
027. 
028.    <View
029.        android:layout_height="1dip"
030.        android:background="#CCCCCC" />
031.  
032.  <LinearLayout
033.        android:orientation="horizontal"
034.        android:layout_width="fill_parent"
035.        android:layout_height="wrap_content"
036.        android:layout_weight="0.1">  
037.      
038.                <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
039.                    android:orientation="horizontal"
040.                    android:layout_width="fill_parent"
041.                    android:layout_height="fill_parent">
042.                    <ImageView
043.                        android:id="@+id/ColPhoto"
044.                        android:layout_width="80dp"
045.                        android:layout_height="80dp"
046.                    />
047.                    <LinearLayout
048.                        android:orientation="vertical"
049.                        android:layout_width="fill_parent"
050.                        android:layout_height="fill_parent">
051.                        <LinearLayout
052.                            android:orientation="horizontal"
053.                            android:layout_width="wrap_content"
054.                            android:layout_height="wrap_content">
055.                            <TextView
056.                                android:layout_width="wrap_content"
057.                                android:layout_height="wrap_content"
058.                                android:text="Name: "
059.                            />
060.                            <TextView android:id="@+id/ColName"
061.                                android:layout_width="wrap_content"
062.                                android:layout_height="wrap_content"
063.                            />
064.                        </LinearLayout>
065.                        <LinearLayout
066.                            android:orientation="horizontal"
067.                            android:layout_width="wrap_content"
068.                            android:layout_height="wrap_content">
069.                            <TextView
070.                                android:layout_width="wrap_content"
071.                                android:layout_height="wrap_content"
072.                                android:text="No: "
073.                            />
074.                            <TextView android:id="@+id/ColPhoneNo"
075.                                android:layout_width="wrap_content"
076.                                android:layout_height="wrap_content"
077.                            />
078.                        </LinearLayout>
079.                        <LinearLayout
080.                            android:orientation="horizontal"
081.                            android:layout_width="wrap_content"
082.                            android:layout_height="wrap_content">
083.                            <TextView
084.                                android:layout_width="wrap_content"
085.                                android:layout_height="wrap_content"
086.                                android:text="Email: "
087.                            />
088.                            <TextView android:id="@+id/ColEmail"
089.                                android:layout_width="wrap_content"
090.                                android:layout_height="wrap_content"
091.                            />
092.                        </LinearLayout>
093.                        <LinearLayout
094.                            android:orientation="horizontal"
095.                            android:layout_width="wrap_content"
096.                            android:layout_height="wrap_content">
097.                            <TextView
098.                                android:layout_width="wrap_content"
099.                                android:layout_height="wrap_content"
100.                                android:text="Address: "
101.                            />
102.                            <TextView android:id="@+id/ColAddress"
103.                                android:layout_width="wrap_content"
104.                                android:layout_height="wrap_content"
105.                            />
106.                        </LinearLayout>
107.                    </LinearLayout>
108.                </LinearLayout>
109. 
110.             
111.    </LinearLayout>
112. 
113.    <View
114.        android:layout_height="1dip"
115.        android:background="#CCCCCC" />
116.           
117.    <LinearLayout
118.      android:id="@+id/LinearLayout1"
119.      android:layout_width="wrap_content"
120.      android:layout_height="wrap_content"
121.      android:padding="5dip" >
122. 
123.        <TextView
124.            android:id="@+id/textView2"
125.            android:layout_width="wrap_content"
126.            android:layout_height="wrap_content"
127.            android:text="By.. ThaiCreate.Com" />
128. 
129.    </LinearLayout>
130.     
131.</TableLayout>


DetailActivity.java
001.package com.myapp;
002. 
003.import java.io.InputStream;
004. 
005.import android.app.Activity;
006.import android.content.ContentResolver;
007.import android.content.ContentUris;
008.import android.content.Intent;
009.import android.database.Cursor;
010.import android.graphics.BitmapFactory;
011.import android.net.Uri;
012.import android.os.Bundle;
013.import android.provider.ContactsContract;
014.import android.view.View;
015.import android.widget.Button;
016.import android.widget.ImageView;
017.import android.widget.TextView;
018. 
019.public class DetailActivity extends Activity  {
020.     
021.     @Override
022.        public void onCreate(Bundle savedInstanceState) {
023.            super.onCreate(savedInstanceState);
024.            setContentView(R.layout.activity_detail);
025.             
026.            //******** Show Detail **********//
027.         
028.            Intent intent= getIntent();
029.            final long PhoneID = Integer.parseInt(intent.getStringExtra("PhoneID"));
030.       
031.            // Photo Bitmap
032.            ImageView imgPhoto = (ImageView) findViewById(R.id.ColPhoto);
033.            imgPhoto.setPadding(10, 10, 10, 10);
034.            final ContentResolver resolver = getContentResolver();
035.            Cursor sCur = resolver.query(
036.                    ContactsContract.Data.CONTENT_URI,
037.                    null,
038.                    ContactsContract.Data.CONTACT_ID + "=" + PhoneID + " AND "
039.                            + ContactsContract.Data.MIMETYPE + "='"
040.                            + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
041.                    null);
042.            if (sCur == null) {
043.                imgPhoto.setImageResource(android.R.drawable.sym_def_app_icon);
044.            }
045.            else
046.            {
047.                Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, PhoneID);
048.                InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
049.                 if (input == null) { 
050.                     imgPhoto.setImageResource(android.R.drawable.sym_def_app_icon);
051.                 }
052.                 else
053.                 {
054.                     imgPhoto.setImageBitmap(BitmapFactory.decodeStream(input));
055.                 }
056. 
057.            }
058.            sCur.close();
059.             
060.            /*** Get Contact Name by ID ***/
061.            Cursor cursor = getContentResolver().query(
062.                    ContactsContract.Contacts.CONTENT_URI,
063.                    null,
064.                    ContactsContract.Contacts._ID +" = ?",
065.                    new String[]{String.valueOf(PhoneID)}, null);
066.             
067.            startManagingCursor(cursor);
068.             
069.            if(cursor != null)
070.            {
071.                cursor.moveToFirst();
072.                // Name
073.                TextView txtName = (TextView) findViewById(R.id.ColName);
074.                txtName.setText(cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
075.                 
076.                // Phone No
077.                Cursor pCur = getContentResolver().query(
078.                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
079.                        null,
080.                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
081.                        new String[]{String.valueOf(PhoneID)}, null);
082.                        // Loop for Phone No
083.                        String pNo = null;
084.                        while (pCur.moveToNext()) {
085.                            String PhoneNo = pCur.getString( pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
086.                            String PhoneType = pCur.getString( pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
087.                            if(pNo != null)
088.                            {
089.                                pNo = pNo + ", " + "(" + fPhoneType(PhoneType) + ")"+ PhoneNo;;
090.                            }
091.                            else
092.                            {
093.                                pNo = "(" + fPhoneType(PhoneType) + ")"+ PhoneNo;
094.                            }
095.                        }
096.                        pCur.close();
097.                // Phone No
098.                TextView txtPhone = (TextView) findViewById(R.id.ColPhoneNo); 
099.                txtPhone.setText(pNo);
100.                 
101.                 
102.                // Email
103.                Cursor eCur = getContentResolver().query(
104.                        ContactsContract.CommonDataKinds.Email.CONTENT_URI,
105.                        null,
106.                        ContactsContract.CommonDataKinds.Email.CONTACT_ID +" = ?",
107.                        new String[]{String.valueOf(PhoneID)}, null);
108.                        // Loop for Email
109.                        String eNo = null;
110.                        while (eCur.moveToNext()) {
111.                            String EmailNo = eCur.getString( eCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
112.                            String EmailType = eCur.getString( eCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
113.                            if(eNo != null)
114.                            {
115.                                eNo = eNo + ", " + "(" + fEmailType(EmailType) + ")"+ EmailNo;;
116.                            }
117.                            else
118.                            {
119.                                eNo = "(" + fEmailType(EmailType) + ")"+ EmailNo;
120.                            }
121.                        }
122.                       eCur.close();
123.                // Email
124.                TextView txtEmail = (TextView) findViewById(R.id.ColEmail); 
125.                txtEmail.setText(eNo);
126.                 
127.                 
128.                // Address
129.                String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
130.                String[] addrWhereParams = new String[]{String.valueOf(PhoneID),
131.                    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
132.                Cursor addrCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
133.                            null, addrWhere, addrWhereParams, null);
134.                while(addrCur.moveToNext()) {
135.                    String poBox = addrCur.getString(
136.                                 addrCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
137.                    String street = addrCur.getString(
138.                                 addrCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.STREET));
139.                    String city = addrCur.getString(
140.                                 addrCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.CITY));
141.                    String state = addrCur.getString(
142.                                 addrCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.REGION));
143.                    String postalCode = addrCur.getString(
144.                                 addrCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
145.                    String country = addrCur.getString(
146.                                 addrCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
147.                    String type = addrCur.getString(
148.                                 addrCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
149.                     
150.                    TextView txtAddress = (TextView) findViewById(R.id.ColAddress); 
151.                    txtAddress.setText(txtAddress.getText() + "- " + street);
152.                }
153.                addrCur.close();
154.                 
155.            }
156.            cursor.close();
157.             
158.             
159.             
160.            // btnBack
161.            final Button Back = (Button)findViewById(R.id.btnBack);
162.            Back.setOnClickListener(new View.OnClickListener() {
163.                public void onClick(View arg0) {
164.                    // TODO Auto-generated method stub
165.                       Intent newActivity = new Intent(DetailActivity.this,MainActivity.class);
166.                       startActivity(newActivity);
167.                }
168.            });
169.             
170.             
171.           
172.        }
173.      
174.     public String fPhoneType(String TypeID)
175.     {
176.            if ("1".equals(TypeID)) {
177.                return "Home";
178.            } else if ("2".equals(TypeID)) {
179.                return "Mobile";   
180.            }
181.        return TypeID;
182.     }
183.      
184.     public String fEmailType(String TypeID)
185.     {
186.            if ("1".equals(TypeID)) {
187.                return "Home";
188.            } else if ("2".equals(TypeID)) {
189.                return "Work"
190.            }
191.        return TypeID;
192.     }
193. 
194.}


เพิ่ม DetailActivity ลงใน AndroidManifest.xml
1.<activity
2.    android:name="DetailActivity"
3.    android:theme="@style/AppTheme"
4.    android:screenOrientation="portrait"           
5.    android:label="@string/title_activity_main" />

เพิ่มลงในไฟล์ AndroidManifest.xml ด้วย



Screenshot

Android People Contact List

แสดงรายชื่อ Contact List บน ListView

Android People Contact List

แสดงรายละเอียดของ Contact เมื่อคลิกในแต่ล่ะรายการของ ListView

   
Hate it
Don't like it
It's ok
Like it
Love it
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2012-07-28 20:20:12 / 2017-03-26 22:20:47
  Download : No files
 Sponsored Links / Related

 
Android Custom Adapter
Rating :

 
Android Rating (Vote) and ListView Part 1
Rating :

 
Android Rating (Vote) and ListView Part 2 (Member Login and Average Rating)
Rating :

 
Android PhoneGap (jQuery Mobile) Create Convert App from Website(URL)
Rating :

 
Android Capture Image and Camera Capture Screenshot (android.view.SurfaceView)
Rating :

 
Android Pull Down to Refresh And Release to Refresh or Update (Part 1)
Rating :

 
Android Pull Down to Refresh And Release to Update (Part 2 , PHP & MySQL)
Rating :


ThaiCreate.Com Forum
Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   





ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2025 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่