Android Api Demos Summit Road (14) Quick Contacts

Source: Internet
Author: User

The main demonstration of this DeMeo is to enable content providers and content resolvers to obtain data from other applications. Content provider provides a unified interface for sharing data across applications, and each content provider of the Android system defines a Content_uri, Each context object in Android, such as activity, has a contentresolver,contentresolver that can get a corresponding content Provider based on Content_uri.
In this example, Startmanagingcursor (c) is used, the cursor is managed, But after android3.0 launched a more secure and flexible cursor management, that is, the use of Loadermanager, this example is on the original basis of the transformation, the use of Loadermanager to complete the demo.
In this example let maniactivity inherit the listactivity, so need to remove setcontentview (), otherwise will error.
Activity_main.xml only does the layout of each entry in order to listactivity. The Quickcontactbadge component is used here, which inherits ImageView, which displays the icon to the left of the contact.

<linearlayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  xmlns:tools  =" Http://schemas.android.com/tools " android:layout_width  = "match_parent"  android:layout_height  =" match_parent " android:orientation  =" horizontal " android:padding  = "5DP" ;     <quickcontactbadge   Android:id  = "@+id/badge"  android:layout_ Width  = "wrap_content"  android:layout_height< /span>= "wrap_content"  android:layout_gravity  = "center_vertical"  android:src  = "@drawable/ic_launcher"  style  =" Android:attr/quickcontactbadgestylesmallwindowsmall "/>     <TextViewandroid:id= "@+id/tv_name"android:layout_width="Match_ Parent "android:layout_height="wrap_content "android:text="@string/hello_ World "android:layout_marginleft="10dp "android:layout_gravity=" Center_vertical " />                                                </linearlayout>

Mainactivity: This uses the Resourcecursoradapter subclass as the adapter for the listactivity.

 Public  class mainactivity extends listactivity {    //Define columns that need to be removed from contacts    Private Finalstring[] Contacts_summary_projection =NewString[] {contacts._id,//0Contacts.display_name,//1Contacts.starred,//2Contacts.times_contacted,//3Contacts.contact_presence,//4CONTACTS.PHOTO_ID,//5Contacts.lookup_key,//6Contacts.has_phone_number//7};Private Static Final intSummary_id_column_index =0;Private Static Final intSummary_name_column_index =1;Private Static Final intSummary_starred_column_index =2;Private Static Final intSummary_times_contacted_column_index =3;Private Static Final intSummary_contact_presence_column_index =4;Private Static Final intSummary_photo_id_column_index =5;Private Static Final intSummary_lookup_key_column_index =6;Private Static Final intSummary_has_phone_number_column_index =7;Private Static Final intloader_id =1;PrivateString selection;PrivateContactlistitemadapter adapter;/** * Android 3.0 provides a more secure and flexible way to load data asynchronously, using Loadermanager * to easily manage cursor Management * *    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Selection ="(("+ Contacts.display_name +"Notnull) and ("+ Contacts.display_name +"! =") and ("+ Contacts.has_phone_number +"=1)";//Flags This flag is used to determine the behavior of the adapter. (ANDROID3.0 recommends that we pass        //Cursoradapter.flag_register_content_observer. The set flag is used to add a        //listener, listening to the parameter cursor data whether there is notconsistent. )adapter =NewContactlistitemadapter (mainactivity. This, R.layout.activity_main,NULL, Cursoradapter.flag_register_content_observer); Setlistadapter (adapter);//Get LoadermanagerLoadermanager manager = Getloadermanager ();//Initialize the loader objectManager.initloader (loader_id,NULL, Myloader);//hand cursor to activity managed startmanagingcursor (c);}PrivateLoadercallbacks<cursor> Myloader =NewLoadercallbacks<cursor> () {//Create a Loader object that carries the cursor        @Override         PublicLoader<cursor>Oncreateloader(intID, Bundle args) {//Create a Cursorloader object The second parameter is the URI of the content provider, and the third parameter is            //To query out which columns, the fourth parameter specifies the condition of the query, the fifth parameter is the parameter of the query,            ///Last parameter means sort in descending order by local language nameCursorloader cl =NewCursorloader (mainactivity. This, Contacts.content_uri, contacts_summary_projection, selection,NULL, Contacts.display_name +"COLLATE localized ASC");returnCl }@Override         Public void onloadfinished(loader<cursor> Loader, cursor cursor) {if(Loader.getid () = = loader_id) {if(Cursor = =NULL) {Toast.maketext (mainactivity. This,"The query failed!" ",0). Show ();return; }if(Cursor.getcount () = =0) {Toast.maketext (mainactivity. This,"The query result is empty!" ",0). Show (); }//Update UI Information                / * * Use content resolver to query the contact based on the contact's URI, the first parameter is the contact URI, the second parameter is * what columns to query, the third parameter specifies the condition of the query, the fourth parameter is the parameter of the query, the most The latter parameter means sorting in descending order of the name in the local language * /Cursor C = getcontentresolver (). Query (Contacts.content_uri, contacts_summary_projection, selection,NULL, Contacts.display_name +"COLLATE localized ASC");            Adapter.swapcursor (c); }        }@Override         Public void Onloaderreset(loader<cursor> Loader) {LOG.I ("TAG","Loader was reseted"); }    };Private  class contactlistitemadapter extends resourcecursoradapter {         Public Contactlistitemadapter(Context context,intLayout, Cursor C,intFlags) {Super(Context, layout, c, flags); }/** * Find individual components */        @Override         PublicViewNewview(Context context, cursor cursor, viewgroup parent) {View view =Super. Newview (context, cursor, parent); Contactlistitemcache cache =NewContactlistitemcache ();            Cache.nameview = (TextView) View.findviewbyid (r.id.tv_name);            Cache.badge = (Quickcontactbadge) View.findviewbyid (R.id.badge); View.settag (cache);returnView }/** * Assigning values to components * /        @Override         Public void BindView(View view, context context, cursor cursor) {Contactlistitemcache cache = (Contactlistitemcache) view.gettag ();//Copy the name of the current query into a variable-length arrayCursor.copystringtobuffer (Summary_name_column_index, Cache.namebuffer);intsize = cache.nameBuffer.sizeCopied; Cache.nameView.setText (Cache.nameBuffer.data,0, size);//For Quickcontactbadge assignment            LongContactId = Cursor.getlong (Summary_id_column_index);            String lookupkey = cursor. getString (SUMMARY_LOOKUP_KEY_COLUMN_INDEX); Uri Lookupuri = Contacts.getlookupuri (Contactid,lookupkey);//system.out.println ("=====:" +lookupuri.tostring ());            //Specify and Quickcontactbadge associated contact URICache.badge.assignContactUri (Lookupuri); }Private  class contactlistitemcache {             PublicTextView Nameview; PublicQuickcontactbadge badge;//Construct a variable-length character array             PublicChararraybuffer Namebuffer =NewChararraybuffer ( -); }    }}

Finally, you need to set permissions to read system contacts in the configuration file:

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

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Api Demos Summit Road (14) Quick Contacts

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.