Android instance-Mobile security Defender (27)-Read Contact number

Source: Internet
Author: User

First, the goal

1, the "26" introduced the method of reading contacts to the project;

2. Select the contact entry to be read, and automatically fill in the text box with its number (pass the data between the activity by means of intent).

Second, the code implementation.

1. Porting the Read contact method to the project.

①. Under the main package (Mobilesafe), create a new Select Contact Human (selectcontactactivity) and create a new "Select Contacts" Layout file in the layout folder (layout) (activity_select_ Contact.xml). Layout file Each contact information is displayed by the ListView component. The layout files and classes are then associated with Setcontentvie within the OnCreate method of choosing a contact human.

Layout file Code:

1<?xml version= "1.0" encoding= "Utf-8"?>2<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"3Android:layout_width= "Match_parent"4android:layout_height= "Match_parent"5android:orientation= "Vertical" >6 7<TextView8Android:layout_width= "Match_parent"9android:layout_height= "50dip"TenAndroid:background= "#00ffff" Oneandroid:gravity= "Center" Aandroid:text= "Please select a contact" -Android:textcolor= "#000000" -Android:textsize= "20sp"/> the  -<ListView -Android:id= "@+id/list_select_contact" -Android:layout_width= "Match_parent" +android:layout_height= "Match_parent" > -</ListView> +  A</LinearLayout>
View Code

②. Copy the adapter code and the Get Contact method code in the main method of the new Select Contact Human (selectcontactactivity) and copy the single contact layout file (Contact_item_view) of the Read contact class to the project layout file. Change the value of the relevant parameter in the adapter (Contactlistview.setadapter ()) code.

New Select Contact Human (selectcontactactivity) code:

1  Public classSelectcontactactivityextendsActivity {2     PrivateListView Contactlistview;3     4 @Override5     protected voidonCreate (Bundle savedinstancestate) {6         Super. OnCreate (savedinstancestate);7 Setcontentview (r.layout.activity_select_contact);8Contactlistview =(ListView) Findviewbyid (r.id.list_select_contact);9list<map<string, string>> listcontact =getcontactinfo ();TenContactlistview.setadapter (NewSimpleadapter ( This, Listcontact, R.layout.contact_item_view, One          Newstring[]{"name", "Phone"},New int[]{r.id.contact_item_name,r.id.contact_item_phone}]); A     } -      -     /** the * Read the contact information in the phone -      * @return -      */ -     PrivateList<map<string, string>>Getcontactinfo () { +         //Get content Parser -Contentresolver resolver =getcontentresolver (); +list<map<string, string>> listcontacts =NewArraylist<map<string,string>>(); A         //gets the URI of the related table for the phone contact database atUri uri = uri.parse ("Content://com.android.contacts/raw_contacts"); -Uri uridata = Uri.parse ("Content://com.android.contacts/data"); -         //querying related data in a data table -cursor cursor = resolver.query (URI,NewString[] {"contact_id" }, -                 NULL,NULL,NULL); -          while(Cursor.movetonext ()) { inString contact_id = cursor.getstring (0); -             if(contact_id! =NULL) { to                 //A specific contact person +Map<string,string> mapcontact =NewHashmap<string, string>(); -Cursor datacursor = Resolver.query (Uridata,Newstring[] { the"Data1", "MimeType"}, "Contact_id=?", *                         NewString[] {contact_id},NULL); $                  while(Datacursor.movetonext ()) {Panax NotoginsengString data1 = datacursor.getstring (0); -String mimetype = datacursor.getstring (1); the                     if("Vnd.android.cursor.item/name". Equals (MimeType)) { +                         //Name of contact person AMapcontact.put ("name", data1); the}Else if("Vnd.android.cursor.item/phone_v2". Equals (MimeType)) { +                         //phone number of the contact person -Mapcontact.put ("Phone", data1); $                     } $                 } -                 //put each contact in a list object - Listcontacts.add (mapcontact); the                 //close the Cursor object - datacursor.close ();Wuyi             } the         } -         //close the Cursor object Wu cursor.close (); -         returnlistcontacts; About     } $}
View Code

③. New Read Contact permission for the project (<uses-permission android:name= "Android.permission.READ_CONTACTS"/>).

2. Select the contact entry to be read, and automatically fill in the text box with its number

①. In select Contact Human (selectcontactactivity), set entry Click events for the Acquired Contacts list (Contactlistview) (Setonitemclicklistener (Onitemclicklistener Listener)), the parameter Onitemclicklistener listener is created by the new Onitemclicklistener () {} and implements its non-implemented method (Onitemclick; > Parent, View view,int position, long id));

②. In the non-implemented method (Onitemclick ()), the Get (int location) method of the Contact information List (listcontact) obtained in the Main method allows you to know where the clicked entry is located (because the inner class needs to access the external class, So to set the contact information List (listcontact) to final type, then get the number of the contact you clicked by using get (Object key) (the parameter is the key name, here is "phone"), and the number is the value of type string.

The code is as follows:

1 String phone = listcontact.get (position). Get ("phone");    
View Code

③. Pass the value to the desired activity by means of intent. New intent, with its Putextra (string name, String value) method, adds the key name (name) and value (value) used during the pass to intent, and then uses the Setresult (int ResultCode, Intent data) sets the return result code (int resultcode) and the dataset for the Intent, Note the Setresult () method must be followed by the finish () method (close the current activity).

The intent pass code is as follows:

1 New Intent (); 2                 Intent.putextra ("Phone", phone); 3                 Setresult (0, intent); 4                 // Close the current page 5                 Finish ();    
View Code

The entire Setonitemclicklistener method code is as follows:

1Contactlistview.setonitemclicklistener (NewOnitemclicklistener () {2 3 @Override4              Public voidOnitemclick (adapterview<?>Parent, view view,5                     intPositionLongID) {6                 //get the corresponding value by clicking on the entry's location and key name7String phone = listcontact.get (position). Get ("Phone"); 8                 //Pass the acquired value to the next activity in the form of intent9Intent Intent =NewIntent ();TenIntent.putextra ("Phone", phone); OneSetresult (0, intent); A                 //Close the current page - finish ();  -             } the});
View Code

④. In the Select Contact method for the third step of the Setup wizard (SelectContact view), start another activity method with a result set (Startactivityforresult (Intent Intent, int requestcode)), you need to always rewrite the onactivityresult (int requestcode, int resultcode, Intent data) method in the OnCreate method.

⑤. In the overridden Onactivityresult method, first determine whether the intent return value (data) is empty, if it is empty, return directly, if not empty, by the intent Getstringextra (String name) to get the corresponding value by the key name , and replacing the "-" in the phone number with the "-" in the charsequence target, charsequence replacement method, has been in line with the Chinese custom.

⑥. Use the SetText (charsequence text) method of the EditText object to place the value obtained in ⑤ into the text box for set security Number (if the text box is not instantiated, you need to instantiate it, set the ID for it in the layout file. The text box object is found through Findviewbyid in the main code, and the value is set by the SetText method.

3. In the third step of the Setup Wizard, save the security number to the configuration file when you click Next

①. Gets the security number in the configuration file through the GetString (string key, String defvalue) of the Sharedpreferences object, with the key in the configuration file. Defvalue represents the default return value when the value corresponding to the key name is not reached. If you saved it, fill it in the Security Number text box.

The code is as follows:

1 et_security_number.settext (sp.getstring ("Security_number", ""));
View Code

    ② . In the in the Set Up wizard, step to next method in the third class ( Slidenext () ), the GetText () method is used to get the contents of the Edit text box, to determine if the text box of the security number is empty, and if NULL, the alert and return, if not empty the Sharedpreferences object is saved to the configuration file

The code is as follows:

1 //get the contents of the Security Number edit box2String Security_number =Et_security_number.gettext (). toString (). Trim ();3         //if it is empty, the reminder then returns4         if(Textutils.isempty (Security_number)) {5Toast.maketext ( This, "No security Number set", 0). Show ();6             return;7         }8         //if not empty, the Sharedpreferences object is saved to the configuration file9Editor Editor =Sp.edit (); TenEditor.putstring ("Security_number", security_number); OneEditor.commit ();
View Code

Android instance-Mobile security Defender (27)-Read Contact number

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.