Android Bulk Add contacts

Source: Internet
Author: User
<span id="Label3"></p><p><p>During the period of graduate students did not write Java code, these days because want to do a statistical web page Word frequency tool, But the use of C + + is not very convenient, and then made a small tool with Java. Turn over the previous files in the computer, found before also did an Android in bulk add contact tools, instantly feel good kind, also sigh time too fast, in the blink of a graduate students will soon be Finished.</p></p><p><p><br></p></p><p><p>Remember to do this batch add contact tool is just come to study, a lot of new students mobile phone number needs to be added, Squad leader finishing out the address Book of students to have a input contact and number to the phone, think of this sin can be affected, So I would like to be able to make the phone directly read the XLS format (excel format) file into the address book, on the Internet to find the general management of the software does not have this gadget, think of it may be due to the tool for Excel file format restrictions it. So want to simply make a forget, this logic is not very complex, at that time also understand a bit of Android development things. And this thing is not very high on android, so I made a gadget to add contacts in Bulk. Now two years did not touch java, a lot of Java API and features have forgotten, the first two days to do which page Word frequency statistics tools are stumbled write out, Android things forget almost almost, just remember to realize the general idea of this Tool.</p></p><p><p><br></p></p><p><p>For a while, I wanted to see what I had done. unfortunately, the computer to replace the system before the development of the SDK is not, but at least the software apk file is still in, so borrowed the Classmate's Samsung mobile phone will be installed on the mobile phone, found to be able to operate normally!!! It's just too comforting to say that the code that was written is pretty good, and there are a lot of comments in the code, and now you can see the idea of the next code, and if you take the time to look at the Android api, it might be quick to get Started. So I'm finishing up Here. Personally feel this thing practicality is quite strong, although not much technical content ^ ^.</p></p><p><p><br></p></p><p><p>Here is the basic structure for implementing this Tool:</p></p><p><p><br></p></p><p><p>To add a contact to the Address Book requires the above basic three steps, but because the first is for themselves and the class classmate, all the default display is our class Classmate's address book, the software run the initialization interface as Follows:</p></p><p><p><br></p></p><p><p><br></p></p><p><p>After the software starts to run there will be a prompt box, prompting the software operation method, Click OK to operate, the top has two buttons, a "add" and "choose file add" button, each line below represents a contact information, from left to right is the contact name, phone number, and whether to choose (whether you choose to add to the address book, the default is to select All).</p></p><p><p><br></p></p><p><p>Remove the checkboxes from the right of the contacts that you don't want to add, and then click the "add One click" button to pour all the selected contacts into your address Book.</p></p><p><p><br></p></p><p><p>If you want to add your own address book, you can put the address Book in the Excel file (the first column in the Excel file as the contact name, the second column phone number), and then click on the "select file to add" button above, the File selection dialog will pop up, select the address book you want to add the XLS file, In the list below, the contacts and numbers in your selected contacts will be displayed, and then click Add to add the selected contacts to your address Book.</p></p><p><p><br></p></p><p><p><br></p></p><p><p><br></p></p><p><p><br></p></p><p><p>The above is the basic design of the program, the specific implementation code as follows, I can now only according to the comments to see what those functions, as well as the logical structure of the program is how to organize, as for the details of programming forget the long.</p></p><p><p>That's Embarrassing.</p></p><p><p><br></p></p><p><p>The class that holds the contact information:</p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">Package Com.example.bean;public class Phonerecord {private int id;private string Name;private string Number;private Boole An ischecked;public phonerecord () {super ();} Public Phonerecord (string name, string number) {super (); this.name = Name;this.number = number;} public int getId () {return id;} public void SetId (int id) {this.id = id;} Public String getName () {return name;} public void SetName (String Name) {this.name = name;} Public String getnumber () {return number;} public void Setnumber (String number) {this.number = number;} public boolean isChecked () {return isChecked;} public void setchecked (boolean isChecked) {this.ischecked = isChecked;}}</pre></pre><br>The main activity, the processing logic of the program is in this class. There are also some response codes for the Buttons.<p><p></p></p><p><p></p></p><pre name="code" class="java">Package Com.example.activity;import Java.io.fileinputstream;import Java.io.inputstream;import java.util.ArrayList; Import java.util.hashmap;import java.util.iterator;import java.util.list;import java.util.map;import jxl. Sheet;import Jxl. Workbook;import Android.app.activity;import Android.app.dialog;import Android.app.progressdialog;import Android.content.contentprovideroperation;import Android.content.operationapplicationexception;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.os.remoteexception;import Android.provider.contactscontract;import Android.provider.contactscontract.commondatakinds.phone;import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.ViewGroup ; Import Android.widget.button;import Android.widget.checkbox;import Android.widget.listview;import Android.widget.simpleadapter;import Android.widget.textview;import Android.widget.toast;import Com.example.bean.phonerecord;import Com.example.contract.r;/** * * @author Xiaxiongfeng * @date 2013/9/1 * @version 1.0 */public Class Mainactivity extends Ac Tivity {//save Data read from Excel file private list<phonerecord> lists;//save to remove some user's contact data private List<phonerecord > Records;//controls for displaying contacts and contact calls in Excel private ListView Listview;//map data to the adapter for the ListView private Simpleadapter adapter;// Map to the data in the control private list<map<string, object>> maps;//the dialog box that pops up when the user taps the "choose Add file" button Private ProgressDialog mpdialog ///save the path of the selected XLS file to the private String filepath;//dialog box labeled static private int openfiledialogid = 0; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); setcontentview (r.layout.activity_main); listview= (ListView) Findviewbyid (r.id.list); lists=readexcel (); mapviewlist (); enterdialog ();} @Overridepublic boolean oncreateoptionsmenu (menu menu) {//inflate The menu; this adds items to the action bar if it is PR Esent.//getmenuinflater (). Inflate (r.menu.main, menu); return true;} @Override @deprecatedprotected Dialog Oncreatedialog (int Id) {//TODO auto-generated method stub if (id==openfiledialogid) {map<string, integer& Gt Xlsfiles = new hashmap<string, integer> (); The following sentence sets the icon for each file type, you need to add the icon to the Resource folder Xlsfiles.put (openfiledialog.sroot, r.drawable.filedialog_root); Root directory icon Xlsfiles.put (openfiledialog.sparent, r.drawable.filedialog_folder_up); Returns the icon for the previous layer Xlsfiles.put (openfiledialog.sfolder, r.drawable.filedialog_folder); folder icon Xlsfiles.put ("xls", r.drawable.filedialog_wavfile); WAV file icon xlsfiles.put (openfiledialog.sempty, r.drawable.filedialog_root); Dialog Dialog = Openfiledialog.createdialog (id, this, "note that only files in XLS format can be selected", new Callbackbundle () {@Override public void callback (bundle Bundle) {//select a file to enter this function, first save the file path in a global variable filepath = bundle.getstring ("path"); Settitle (filepath); Put file pathAppears on the header//reads the Excel file, at this point, because FilePath is not empty, Readexcel reads the data from the path specified by filepath without using the default data lists=r Eadexcel (); The data to be read is mapped to the ListView control using the adapter Mapviewlist (); Hide the "one-click add" button ((button) Findviewbyid (r.id.defaultbtnid)). setvisibility (view.invisible); Displays the Add button ((button) Findviewbyid (r.id.realaddbtn)). setvisibility (view.visible); Let the Select File Add button lose focus (button) Findviewbyid (r.id.otherbtnid)). setfocusable (false); }}, ". xls;", xlsfiles); Return dialog; } return null; }/** * Convert data read from Excel into Map and display it to the control */public void Mapviewlist () {maps=new arraylist<map<string,object> > ();iterator<phonerecord> iter=lists.iterator (); while (iter.hasnext ()) {phonerecord record=iter.next (); map<string,object> map=new hashmap<string, object> (); map.put ("name", record.getname ()); map.put ("numbeR ", record.getnumber ()); map.put (" isChecked ", record.ischecked ()); maps.add (map);} Adapter=new simpleadapter (this, maps, r.layout.activity_main_item, new string[]{"name", "number"}, new Int[]{r.id.name , R.id.number}) {@Overridepublic View GetView (int position, view Convertview,viewgroup parent) {//TODO auto-generated Method Stubview View=super.getview (position, convertview, parent); final hashmap<string,object> hash= (HashMap <string, object>) This.getitem (position); CheckBox cb= (checkbox) View.findviewbyid (r.id.checked); cb.setchecked ((Boolean) hash.get ("isChecked"); Cb.setonclicklistener (new view.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubhash.put ("isChecked", (CheckBox) v). isChecked ());}); Return view;}; Listview.setadapter (adapter);} Read data from Excel save to Phonerecord class public list<phonerecord> readexcel () {list<phonerecord> lists=new Arraylist<phonerecord> (); try {//inputstream is = new FileInputStream ("mnt/sdcarD/test.xls "); InputStream is=getassets (). Open ("contact.xls"); Only the Select File dialog box pops up and the file is selected to enter this selection branch, otherwise the default is to add the System's own address book if (filepath!=null) {is=new fileinputstream (filepath);} Workbook book = Workbook.getworkbook (is); Book.getnumberofsheets (); Get the first sheet object Sheet Sheet = Book.getsheet (0); int Rows = Sheet.getrows (); for (int i = 0; i < Rows; i++) {phonerecord record=new Phonerecord (); String Name=sheet.getcell (0,i). getcontents (); String Number=sheet.getcell (1,i). getcontents (); If (name==null| | Name.equals ("") | | number==null| | Number.equals ("")) {continue; } record.setname (name); Record.setnumber (number); Record.setchecked (true); Lists.add (record);} } catch (Exception E) {//todo:handle exceptione.printstacktrace ();} Return lists;} /** * How to save data to your contacts * @param list */public void CopyphonerEcords (list<phonerecord> List) {arraylist<contentprovideroperation> ops = new arraylist< contentprovideroperation> (); int rawcontactinsertindex;if (list==null| | List.size () ==0) {return;} for (int i = 0; i < list.size (); I++) {rawcontactinsertindex = ops.size (); Ops.add (contentprovideroperation.newinsert (ContactsContract.RawContacts.CONTENT_URI) Withvalue (contact sContract.RawContacts.ACCOUNT_TYPE, null). withvalue (ContactsContract.RawContacts.ACCOUNT_NAME, Null) . withyieldallowed (true). Build ()); Ops.add (contentprovideroperation.newinsert (ContactsContract.Data.CONTENT_URI). withvaluebackreference (C ontactscontract.data.raw_contact_id,rawcontactinsertindex). Withvalue (ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE). Withvalue (contactscontract.commondAtakinds.structuredname.display_name,list.get (i). getName ()). withyieldallowed (true) . Build ()); Ops.add (contentprovideroperation.newinsert (ContactsContract.Data.CONTENT_URI). withvaluebackreference (C ontactsContract.Data.RAW_CONTACT_ID, rawcontactinsertindex). Withvalue (ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE). Withvalue (contact sContract.CommonDataKinds.Phone.NUMBER, list.get (i). getnumber ()). withvalue (contactscontract.commondata Kinds.Phone.TYPE, phone.type_mobile). withyieldallowed (true). Build ()); } Try {///this is called in bulk add This.getcontentresolver (). applybatch (contactscontract.authority, ops); } catch (remoteexception e) {//TODO auto-generated catch blocke.printstacktrace ();} catch ( Operationapplicationexception e) {//TODO auto-generated catchBlocke.printstacktrace ();} }//this Handler has only one function, to accept the message after closing the prompt progress box handler handler=new handler () {public void Handlemessage (android.os.Message Msg) { Mpdialog.dismiss ();};}; Handler toasthandler=new Handler () {public void handlemessage (android.os.Message msg) {switch (msg.what) {case 1: Toast.maketext (getapplicationcontext (), "bulk Add complete!" ", toast.length_long). show (); break;case 2:toast.maketext (getapplicationcontext ()," Please select a contact! " ", toast.length_long). Show (); break;default:break;}};};/ * * "one-click add" button Response event * @param view */public void Defaultadds (view view) {//default Add contacts event adds ();} /** * "select File add" button Response event * @param view */public void Otheradds (view view) {//showDialog (openfiledialogid);//when "select file add" is clicked, the " One-click Add button is set to not get Focus//button bt= (button) Findviewbyid (r.id.defaultbtnid);//bt.setfocusable (false);// Pop-up File selection dialog box ShowDialog (openfiledialogid);} /** * "add" Button Response event * @param view */public void Realadd (view view) {//add data adds ();//add the "one button" button to hide (button) Findviewbyid ( r.id.defaultbtnid)). setvisibility (view.invisible);//add "select file to button" to get focus (butTon) Findviewbyid (r.id.otherbtnid)). setfocusable (true);} /** * True Add process * First you need to traverse the data read from Excel to determine if their ischecked property is True * is true by default, but if the user clicks the checkbox in the listview, this property will be false */public void adds () {int size=maps.size (); records=new arraylist<phonerecord> (); int i=0;for (; i < size; i++) { Phonerecord record=new Phonerecord (); map<string,object> tmp=maps.get (i); record.setname ((string) tmp.get ("name"); record.setnumber ((string) Tmp.get ("number")), if ((Boolean) tmp.get ("isChecked")) {records.add (record);}} Pop-up Tip Progress Box Mpdialog=progressdialog.show (this, "prompt", "add address book, wait ...");//open a new thread for the Runnable () {@ overridepublic void Run () {//TODO auto-generated method stubmessage msg=new Message ()//add action on new thread if (records!=null& Amp;&records.size ()!=0) {copyphonerecords (records);//pop-up A word that prompts the bulk operation to complete Msg.what=1;toasthandler.sendmessage (msg) ;//when The add operation is complete, send a message to the prompt progress box and let the Progress box close Handler.sendemptymessage (0);} Else{msg.what=2;toasthandler.sendmessage (msg); handler.sendemptymessage (0);}}). Start ();} The prompt interface at the start of the publIC void Enterdialog () {final Dialog dialog=new Dialog (this,r.style.popupdialog);d Ialog.setcontentview ( R.layout.verify_dialog);d ialog.setcancelable (false); TextView message= (TextView) dialog.getwindow (). findviewbyid (r.id.messagetxt); message.settext (this.getstring ( r.string.defaulttxt)); Button okbtn= (button) dialog.getwindow (). Findviewbyid (r.id.messagebtn); Okbtn.setonclicklistener (new onclicklistener () {@Override public void OnClick (View V {if (dialog!=null && dialog.isshowing ()) {dialog.dismiss (); } } }); If (dialog!=null &&!dialog.isshowing ()) {dialog.show (); }}}</pre><br>The entire project source code DOWNLOAD.<p><p></p></p><p><p><br></p></p> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p> <p><p>Android Bulk Add contacts</p></p></span>

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.