Android load local Contacts implementation method _android

Source: Internet
Author: User
Tags xmlns
First build the layout file, the interface is very simple, is a search box and the following contact list:

Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
Android:background= "#FFD3D7DF"
android:orientation= "Vertical"
android:padding= "0dip" >
<relativelayout
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:layout_marginleft= "3dip"
android:layout_marginright= "3dip"
android:layout_margintop= "3dip" >
<edittext
Android:id= "@+id/search_view"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:hint= "@string/hint_search_contacts"
android:paddingleft= "32dip"
Android:singleline= "true"
Android:textsize= "16sp"/>
<imageview
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:layout_alignleft= "@id/search_view"
Android:layout_centervertical= "true"
android:layout_marginleft= "3dip"
android:src= "@drawable/contacts"/>
</RelativeLayout>
<listview
Android:id= "@+id/contact_list"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
Android:layout_marginbottom= "0dip"
android:layout_marginleft= "0dip"
android:layout_marginright= "0dip"
android:layout_margintop= "0dip"
Android:layout_weight= "1.0"
Android:cachecolorhint= "#00000000"
Android:divider= "#00000000"
android:dividerheight= "0.1px"
Android:fadingedge= "None"
Android:footerdividersenabled= "false"
Android:listselector= "@null"
Android:paddingbottom= "0dip"
android:paddingleft= "0dip"
android:paddingright= "0dip"
android:paddingtop= "0dip"/>
</LinearLayout>

Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout
Xmlns:android= "Http://schemas.android.com/apk/res/android"
android:orientation= "Horizontal"
android:layout_height= "Wrap_content"
Android:layout_width= "Fill_parent"
android:paddingtop= "2dip"
Android:paddingbottom= "2dip"
android:background= "@color/list_item_background" >
<imageview
Android:id= "@+id/photo"
android:layout_height= "Wrap_content"
Android:layout_width= "Wrap_content"
android:layout_marginleft= "5dip"
Android:layout_gravity= "Center_vertical"
android:layout_weight= "1"
android:src= "@drawable/default_avatar"
/>
<linearlayout
android:orientation= "Vertical"
android:layout_height= "Wrap_content"
Android:layout_width= "Wrap_content"
Android:layout_gravity= "Center_vertical"
android:layout_marginleft= "5dip"
Android:layout_weight= ">"
<textview android:id= "@+id/text1"
Android:typeface= "Serif"
Android:singleline= "true"
style= "@style/list_font_main_text"/>

<linearlayout
android:orientation= "Horizontal"
android:layout_height= "Wrap_content"
Android:layout_width= "Wrap_content"
android:layout_margintop= "3dip" >
<textview android:id= "@+id/text2"
Android:typeface= "Serif"
Android:singleline= "true"
style= "@style/list_font_detail_text"/>

<textview android:id= "@+id/text3"
Android:ellipsize= "Marquee"
android:layout_marginleft= "3dip"
android:marqueerepeatlimit= "Marquee_forever"
Android:scrollhorizontally= "true"
style= "@style/list_font_detail_text"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>

Then the Click event: (Click to return the selected contact number to the input box)

Copy Code code as follows:

Get the Contact button object and bind the onclick click event
Phonebutton = (Button) Findviewbyid (R.id.find_phone);
Phonebutton.setonclicklistener (New Onclicklistener () {
public void OnClick (View v) {
Select the number from the contact, and then process the callback result by Onactivityresult () method
Intent Intent = new Intent (context, contactsactivity.class);
Startactivityforresult (Intent, Request_code);
}
});
/**
* Select the callback handler function for the contact person
*/
@Override
public void Onactivityresult (int reqcode, int resultcode, Intent data) {
Super.onactivityresult (Reqcode, ResultCode, data);
if (ResultCode = = RESULT_OK) {
Switch (reqcode) {
Case Request_code:
String phone = Data.getstringextra ("Phone");
Phoneedittext.settext (phone);
Break
}
}
}


The following is the activity of the Contact interface:
Copy Code code as follows:

/**
* Show contacts on user's phone
*
* @author Mr.Z
* @time 2012-3-21
*
*/
public class Contactsactivity extends activity {
Private context ctx = Contactsactivity.this;
Private TextView Toptitletextview;
Private ListView ListView = null;
listPrivate EditText Contactssearchview;
Private ProgressDialog progressdialog = null;
Data loading completed messages
Private final int message_succ_load = 0;
The message that the data query completes
Private final int message_succ_query = 1;
Private Handler Handler = new Handler () {
@Override
public void Handlemessage (msg) {
Super.handlemessage (msg);
Switch (msg.what) {
Case Message_succ_load:
Listview.setadapter (New Contactsadapter (CTX));
Progressdialog.dismiss ();
Break
Case Message_succ_query:
Listview.setadapter (New Contactsadapter (CTX));
Break
}
}
};
protected void OnCreate (Bundle savedinstancestate) {
Requestwindowfeature (Window.feature_no_title);
GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Super.oncreate (savedinstancestate);
This.setcontentview (r.layout.contacts);
Display contacts using ListView
ListView = (ListView) Findviewbyid (r.id.contact_list);
Loadandsavecontacts ();
The Click event that binds the ListView item
Listview.setonitemclicklistener (New Onitemclicklistener () {
@SuppressWarnings ("Unchecked")
public void Onitemclick (adapterview<?> adapterview, view view, int position, long _id) {
hashmap<string, string> map = (hashmap<string, string>) adapterview.getitematposition (position);
String phone = map.get ("Phone");
The cell phone number preprocessing (remove the number before the +86, the first and last space, "-" number, etc.)
Phone = Phone.replaceall ("^ (\\+86)", "");
Phone = Phone.replaceall ("^ (86)", "");
Phone = Phone.replaceall ("-", "");
Phone = Phone.trim ();
If the current number is not a mobile number
if (! Saleutil.isvalidphonenumber (phone))
Saleutil.createdialog (CTX, R.string.dialog_title_tip, getString (R.string.alert_contacts_error_phone));
else {
Intent Intent = new Intent ();
Intent.putextra ("Phone", phone);
Setresult (RESULT_OK, intent);
Close the current window
Finish ();
}
}
});
Contactssearchview = (edittext) Findviewbyid (R.id.search_view);
Contactssearchview.addtextchangedlistener (New Textwatcher () {
public void aftertextchanged (Editable s) {
}
public void beforetextchanged (charsequence s, int start, int count, int after) {
}
public void ontextchanged (charsequence s, int start, int before, int count) {
Querycontacts (S.tostring ());
}
});
}
/**
* Load and store contact data
*/
private void Loadandsavecontacts () {
ProgressDialog = progressdialog.show (CTX, NULL, "Loading contact data ...");
New Thread () {
@Override
public void Run () {
Get Contact data
Contactslist = Findcontacts ();
Temporarily store contact data
Dbhelper.savecontacts (CTX, contactslist);
Send Message notification Update UI
Handler.sendemptymessage (Message_succ_load);
}
}.start ();
}
/**
* Get contacts from local temp library based on criteria
*
* @param keyWord Query Keywords
*/
private void Querycontacts (final String KeyWord) {
New Thread () {
@Override
public void Run () {
Get Contact data
Contactslist = Dbhelper.findcontactsbycond (CTX, KeyWord);
Send Message notification Update UI
Handler.sendemptymessage (Message_succ_query);
}
}.start ();
}
/**
* Get Mobile contact information
*
* @return List*/
Public listlistQuery Contact
Cursor contactscursor = Ctx.getcontentresolver (). query (ContactsContract.Contacts.CONTENT_URI, NULL, NULL, NULL, Phonelookup.display_name + "COLLATE localized ASC");
Index of Names
int nameindex = 0;
Contact person Name
String name = NULL;
Contact the ID of the head image
String photoid = null;
ID index value of contact person
String contactsid = null;
Query the phone number of a contact person
Cursor phonecursor = null;
while (Contactscursor.movetonext ()) {
Nameindex = Contactscursor.getcolumnindex (phonelookup.display_name);
Name = Contactscursor.getstring (Nameindex);
PhotoID = contactscursor.getstring (Contactscursor.getcolumnindex (phonelookup.photo_id));
Contactsid = contactscursor.getstring (Contactscursor.getcolumnindex (contactscontract.contacts._id));
Phonecursor = Getcontentresolver (). query (ContactsContract.CommonDataKinds.Phone.CONTENT_URI, NULL, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + Contactsid, NULL, NULL);
Traverse the contact number (one person corresponds to more than one phone number)
while (Phonecursor.movetonext ()) {
hashmap<string, string> phonemap = new hashmap<string, string> ();
Add a contact person's name
Phonemap.put ("name", name);
Add a contact Avatar
Phonemap.put ("Photo", photoid);
Add phone number
Phonemap.put ("Phone", Phonecursor.getstring (Phonecursor.getcolumnindex) ( ContactsContract.CommonDataKinds.Phone.NUMBER)));
Add number type (home phone, mobile phone number, Unit telephone, etc.)
Phonemap.put ("type", GetString (ContactsContract.CommonDataKinds.Phone.getTypeLabelResource phonecursor.getint ( Phonecursor.getcolumnindex (ContactsContract.CommonDataKinds.Phone.TYPE))));
List.add (PHONEMAP);
}
Phonecursor.close ();
}
Contactscursor.close ();
return list;
}
/**
* Get contact Avatar
*
* @param context Environment
* @param photoid Avatar ID
* @return Bitmap
*/
public static Bitmap Getphoto (context context, String photoid) {
Bitmap Bitmap = Bitmapfactory.decoderesource (Context.getresources (), R.drawable.default_avatar);
if (photoid!= null && "". Equals (PhotoID)) {
string[] projection = new string[] {ContactsContract.Data.DATA15};
String selection = "contactscontract.data._id =" + photoid;
Cursor cur = context.getcontentresolver (). Query (ContactsContract.Data.CONTENT_URI, projection, selection, NULL, NULL) ;
if (cur!= null) {
Cur.movetofirst ();
byte[] Contacticon = null;
Contacticon = Cur.getblob (Cur.getcolumnindex (ContactsContract.Data.DATA15));
if (Contacticon!= null) {
Bitmap = Bitmapfactory.decodebytearray (Contacticon, 0, contacticon.length);
}
}
}
return bitmap;
}
/**
* Custom Contact person Adapter
*/
Class Contactsadapter extends Baseadapter {
Private Layoutinflater inflater = null;
Public Contactsadapter (context ctx) {
Inflater = Layoutinflater.from (CTX);
}
public int GetCount () {
return Contactslist.size ();
}
Public Object getitem (int position) {
return Contactslist.get (position);
}
public long getitemid (int position) {
return position;
}
Public View GetView (int position, View Convertview, ViewGroup parent) {
Viewholder holder = null;
if (Convertview = = null) {
Holder = new Viewholder ();
Convertview = inflater.inflate (R.layout.contacts_listview_item, NULL);
Holder.text1 = (TextView) Convertview.findviewbyid (R.ID.TEXT1);
Holder.text2 = (TextView) Convertview.findviewbyid (R.ID.TEXT2);
HOLDER.TEXT3 = (TextView) Convertview.findviewbyid (R.ID.TEXT3);
Convertview.settag (holder);
} else {
Holder = (viewholder) convertview.gettag ();
}
Holder.text1.setText (Contactslist.get (position). Get ("name");
Holder.text2.setText (Contactslist.get (position). Get ("type"));
Holder.text3.setText (Contactslist.get (position). Get ("phone"));
return convertview;
}
Public final class Viewholder {
Private TextView Text1;
Private TextView Text2;
Private TextView Text3;
}
}
}

Query method statement:
Copy Code code as follows:

/**
* Query contact data based on criteria
*
* @param context Environment
* @param keyWord Query Keywords
* @return List*/
public static listlistSqlitedatabase db = dbhelper.getsqlitedb (context);
String sql = "SELECT * from Contacts where name" "+ KeyWord +"% ' or name_alias like ' + KeyWord + '% ' ORDER by _id ";
Querying data
Cursor Cursor = db.rawquery (sql, NULL);
while (Cursor.movetonext ()) {
hashmap<string, string> map = new hashmap<string, string> ();
Map.put ("Name", Cursor.getstring (Cursor.getcolumnindex ("name"));
Map.put ("Phone"), Cursor.getstring (Cursor.getcolumnindex ("Phone"));
Map.put ("type", Cursor.getstring (Cursor.getcolumnindex ("type")));
Map.put ("Photo", Cursor.getstring (Cursor.getcolumnindex ("photo"));
List.add (map);
}
Cursor.close ();
Db.close ();
return list;
}
/**
* Store Contact information
*
* @param context Environment
* @param contactslist Contact List
*/
public static void Savecontacts (context context, listSqlitedatabase db = dbhelper.getsqlitedb (context);
Open transaction Control
Db.begintransaction ();
try {
Clear the Contact data first
Db.execsql ("drop table if exists contacts");
Db.execsql ("CREATE Table Contacts" (_id integer NOT null primary key AutoIncrement, name varchar (m), Name_alias varchar (10) , phone varchar (m), type varchar, photo varchar (50)) ";
String sql = null;
For (hashmap<string, string> contactsmap:contactslist) {
sql = String.Format (insert into Contacts (Name,name_alias,phone,type,photo) values ('%s ', '%s ', '%s ', '%s ', '%s '), Contactsmap.get ("name"), Saleutil.getpinyinfirstalphabet (Contactsmap.get ("name")), Contactsmap.get ("Phone"), Contactsmap.get ("type"), Contactsmap.get ("photo"));
Db.execsql (SQL);
}
Set transaction flag to successful
Db.settransactionsuccessful ();
finally {
End transaction
Db.endtransaction ();
Db.close ();
}
}

Tool class:
Copy Code code as follows:

/**
* Determine whether the customer's mobile phone number is in accordance with the rules
*
* @param userphone Customer mobile phone number
* @return True | False
*/
public static Boolean Isvalidphonenumber (String userphone) {
if (null = = Userphone | | "". Equals (Userphone))
return false;
Pattern p = pattern.compile ("^0?1[0-9]{10}");
Matcher m = P.matcher (Userphone);
return m.matches ();
}
/**
* Get Chinese Pinyin first letter
*
* @param Chinese Chinese
* @return Pinyin First Letter
*/
public static string Getpinyinfirstalphabet (string Chinese) {
String convert = "";
for (int j = 0; J < Chinese.length (); j + +) {
Char word = Chinese.charat (j);
string[] Pinyinarray = Pinyinhelper.tohanyupinyinstringarray (word);
if (Pinyinarray!= null) {
Convert + + pinyinarray[0].charat (0);
} else {
Convert + + word;
}
}
return convert;
}

Finally add the authority on the line;
Copy Code code as follows:

<!--permissions to access contacts-->
<uses-permission android:name= "Android.permission.READ_CONTACTS"/>
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.