首页 > 代码库 > android 导入数据(通讯录)

android 导入数据(通讯录)

接着android 中导出数据 一文,下面介绍在android中导入数据的思路:

1、将数据从文本中读取出来

2、封装处理成自己想要的对象或模型

3、将处理好的数据对象插入自己应用的数据库中

4、更新UI显示

下面仍以导入联系人至系统中为例,若是导入自己的应用中,思路一样甚至更简单,代码如下:

注:我的联系人.txt的格式即为android 中导出数据 一文生成的格式

MainActivity:

  1 package com.home.impcontact;  2    3 import java.io.File;  4 import java.io.FileInputStream;  5 import java.io.IOException;  6 import java.util.ArrayList;  7 import android.app.Activity;  8 import android.app.AlertDialog;  9 import android.content.ContentUris; 10 import android.content.ContentValues; 11 import android.content.Context; 12 import android.content.DialogInterface; 13 import android.net.Uri; 14 import android.os.Bundle; 15 import android.os.Environment; 16 import android.os.Handler; 17 import android.os.Message; 18 import android.provider.ContactsContract; 19 import android.provider.ContactsContract.RawContacts; 20 import android.provider.ContactsContract.CommonDataKinds.Phone; 21 import android.provider.ContactsContract.CommonDataKinds.StructuredName; 22 import android.provider.ContactsContract.Contacts.Data; 23 import android.view.View; 24 import android.view.View.OnClickListener; 25 import android.widget.Button; 26 import android.widget.TextView; 27 import android.widget.Toast; 28   29 public class MainActivity extends Activity implements OnClickListener { 30     private Button btn;// 导入按钮 31     private TextView show;// 显示结果的文本框 32     private Thread addThread;// 增加联系人线程 33     private static final int ADD_FAIL = 0;// 导入失败标识 34     private static final int ADD_SUCCESS = 1;// 导入成功标识 35     private static int successCount = 0;// 导入成功的计数 36     private static int failCount = 0;// 导入失败的计数 37     // 默认文件路劲,实际情况应作相应修改或从界面输入或浏览选择 38     private static final String PATH = Environment 39             .getExternalStorageDirectory() + "/我的联系人.txt"; 40   41     @Override 42     protected void onCreate(Bundle savedInstanceState) { 43         super.onCreate(savedInstanceState); 44         setContentView(R.layout.main); 45         init(); 46     } 47   48     /** 49      * 初始化组件 50      */ 51     private void init() { 52         btn = (Button) findViewById(R.id.main_btn); 53         btn.setOnClickListener(this); 54         show = (TextView) findViewById(R.id.main_tv); 55     } 56   57     @Override 58     public void onClick(View v) { 59         if (v == btn) { 60             addContact(); 61         } 62     } 63   64     /** 65      * 导入联系人入口 66      */ 67     private void addContact() { 68         if (!new File(PATH).exists()) { 69             Toast.makeText(this, "文件不存在!", Toast.LENGTH_SHORT).show(); 70             show.setText("文件不存在!"); 71             return; 72         } 73         if (addThread != null) { 74             addThread.interrupt(); 75             addThread = null; 76         } 77         addThread = new Thread(new AddRunnable(this, PATH)); 78         createDialog(this, "警告", "确保你是第一次导入,重复导入会创建新的联系人,请慎用!"); 79     } 80   81     /** 82      * 创建提示对话框 83      *  84      * @param context 85      * @param title 86      * @param message 87      */ 88     private void createDialog(Context context, String title, String message) { 89         AlertDialog.Builder builder = new AlertDialog.Builder(context); 90         builder.setTitle(title); 91         builder.setMessage(message); 92         builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { 93             public void onClick(DialogInterface dialog, int whichButton) { 94                 startAddContact(); 95             } 96         }); 97         builder.setNeutralButton("取消", new DialogInterface.OnClickListener() { 98             public void onClick(DialogInterface dialog, int whichButton) { 99                 dialog.cancel();100             }101         });102         builder.show();103     }104  105     /**106      * 开启导入线程107      */108     private void startAddContact() {109         setAddWidgetEnabled(false);110         show.setText("正在导入联系人...");111         if (addThread != null) {112             addThread.start();113         }114     }115  116     class AddRunnable implements Runnable {117         private Context context;118         private String path;119  120         public AddRunnable(Context context, String path) {121             this.path = path;122             this.context = context;123         }124  125         @Override126         public void run() {127             boolean result = importContact(context, path);128             if (result) {129                 handler.sendEmptyMessage(ADD_SUCCESS);130             } else {131                 handler.sendEmptyMessage(ADD_FAIL);132             }133         }134     }135  136     /**137      * 处理UI相关的handler138      */139     private Handler handler = new Handler() {140         @Override141         public void handleMessage(Message msg) {142             switch (msg.what) {143             case ADD_FAIL:144                 show.setText("导入联系人失败");145                 setAddWidgetEnabled(true);146                 break;147             case ADD_SUCCESS:148                 show.setText(String.format("导入联系人成功 %d 条,失败 %d 条",149                         successCount, failCount));150                 setAddWidgetEnabled(true);151                 break;152             }153         }154     };155  156     /**157      * 设置导入组件的可用性158      * 159      * @param enabled160      */161     private void setAddWidgetEnabled(boolean enabled) {162         btn.setEnabled(enabled);163         if (!enabled) {164             show.setText("");165         }166     }167  168     /**169      * 导入联系人170      * 171      * @param context172      * @param path173      * @return174      */175     private boolean importContact(Context context, String path) {176         successCount = 0;177         failCount = 0;178         try {179             ArrayList<contactinfo> list = readFromFile(path);180             if (list == null) {181                 return false;182             }183             for (int i = 0; i < list.size(); i++) {184                 ContactInfo info = list.get(i);185                 if (doAddContact(context, info)) {186                     successCount++;187                 }188             }189         } catch (Exception e) {190             e.printStackTrace();191             return false;192         }193         return true;194     }195  196     /**197      * 读取联系人并封装成ContactInfo对象集合198      * 199      * @param path200      * @return contactsList201      */202     private ArrayList<contactinfo> readFromFile(String path) {203         ArrayList<string> strsList = doReadFile(path);204         if (strsList == null) {205             return null;206         }207         ArrayList<contactinfo> contactsList = handleReadStrs(strsList);208         return contactsList;209     }210  211     /**212      * 将读出来的内容封装成ContactInfo对象集合213      * 214      * @param strsList215      * @return216      */217     private ArrayList<contactinfo> handleReadStrs(ArrayList<string> strsList) {218         ArrayList<contactinfo> contactsList = new ArrayList<contactinfo>();219         for (int i = 0; i < strsList.size(); i++) {220             String info = strsList.get(i);221             String[] infos = info.split("\\s{2,}");222             String displayName = null;223             String mobileNum = null;224             String homeNum = null;225             switch (infos.length) {226             case 0:227                 continue;228             case 1:229                 displayName = infos[0];230                 break;231             case 2:232                 displayName = infos[0];233                 if (infos[1].length() >= 11) {234                     mobileNum = infos[1];235                 } else {236                     homeNum = infos[1];237                 }238                 break;239             default:240                 // length >= 3241                 displayName = infos[0];242                 mobileNum = infos[1];243                 homeNum = infos[2];244             }245             if (displayName == null || "".equals(displayName)) {246                 failCount++;247                 continue;248             }249             contactsList.add(new ContactInfo(displayName, mobileNum, homeNum));250         }251         return contactsList;252     }253  254     /**255      * 读取文件内容256      * 257      * @param path258      * @return259      */260     private ArrayList<string> doReadFile(String path) {261         FileInputStream in = null;262         ArrayList<string> arrayList = new ArrayList<string>();263         try {264             byte[] tempbytes = new byte[1 << 24];265             in = new FileInputStream(path);266             while (in.read(tempbytes) != -1) {267                 int length = 0;268                 int first = length;269                 for (int i = 0; i < tempbytes.length; i++) {270                     if (tempbytes[i] == ‘\n‘) {271                         length = i;272                         byte[] nowBytes = new byte[length - first];273                         System.arraycopy(tempbytes, first, nowBytes, 0, length274                                 - first);275                         arrayList.add(new String(nowBytes, "utf-8").trim());276                         first = i + 1;277                     }278                 }279  280             }281         } catch (Exception e1) {282             return null;283         } finally {284             if (in != null) {285                 try {286                     in.close();287                 } catch (IOException e1) {288                     return null;289                 }290             }291         }292         return arrayList;293     }294  295     /**296      * 向数据库表插入联系人信息297      * 298      * @param context299      * @param contactInfo300      * @return301      */302     private boolean doAddContact(Context context, ContactInfo contactInfo) {303         try {304             ContentValues contentValues = new ContentValues();305             Uri uri = context.getContentResolver().insert(306                     RawContacts.CONTENT_URI, contentValues);307             long rowId = ContentUris.parseId(uri);308  309             String name = contactInfo.getDisplayName();310             String mobileNum = contactInfo.getMobileNum();311             String homeNum = contactInfo.getHomeNum();312  313             // 插入姓名314             if (name != null) {315                 contentValues.clear();316                 contentValues.put(Data.RAW_CONTACT_ID, rowId);317                 contentValues.put(Data.MIMETYPE,318                         StructuredName.CONTENT_ITEM_TYPE);319                 int index = name.length() / 2;320                 String displayName = name;321                 String givenName = null;322                 String familyName = null;323                 // 检查是否是英文名称324                 if (checkEnglishName(displayName) == false) {325                     givenName = name.substring(index);326                     familyName = name.substring(0, index);327                 } else {328                     givenName = familyName = displayName;329                 }330                 contentValues.put(StructuredName.DISPLAY_NAME, displayName);331                 contentValues.put(StructuredName.GIVEN_NAME, givenName);332                 contentValues.put(StructuredName.FAMILY_NAME, familyName);333                 context.getContentResolver().insert(334                         ContactsContract.Data.CONTENT_URI, contentValues);335             }336  337             if (mobileNum != null) {338                 // 插入手机电话339                 contentValues.clear();340                 contentValues.put(Data.RAW_CONTACT_ID, rowId);341                 contentValues.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);342                 contentValues.put(Phone.NUMBER, mobileNum);343                 contentValues.put(Phone.TYPE, Phone.TYPE_MOBILE);344                 context.getContentResolver().insert(345                         ContactsContract.Data.CONTENT_URI, contentValues);346             }347  348             if (homeNum != null) {349                 // 插入家庭号码350                 contentValues.clear();351                 contentValues.put(Data.RAW_CONTACT_ID, rowId);352                 contentValues.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);353                 contentValues.put(Phone.NUMBER, homeNum);354                 contentValues.put(Phone.TYPE, Phone.TYPE_HOME);355                 context.getContentResolver().insert(356                         ContactsContract.Data.CONTENT_URI, contentValues);357             }358         } catch (Exception e) {359             return false;360         }361         return true;362     }363  364     /**365      * 检查是否是英文名称366      * 367      * @param name368      * @return369      */370     private boolean checkEnglishName(String name) {371         char[] nameChars = name.toCharArray();372         for (int i = 0; i < nameChars.length; i++) {373             if ((nameChars[i] >= ‘a‘ && nameChars[i] <= ‘z‘)374                     || (nameChars[i] >= ‘A‘ && nameChars[i] <= ‘Z‘)) {375                 continue;376             }377             return false;378         }379         return true;380     }381 }

联系人实体类ContactInfo:

 1 package com.home.impcontact; 2   3 public class ContactInfo { 4     /** 名称 */ 5     private String displayName; 6     /** 手机号 */ 7     private String mobileNum; 8     /** 家庭电话 */ 9     private String homeNum;10  11     public ContactInfo(String displayName, String mobileNum, String homeNum) {12         this.displayName = displayName;13         this.mobileNum = mobileNum;14         this.homeNum = homeNum;15     }16  17     public String getDisplayName() {18         return displayName;19     }20  21     public String getMobileNum() {22         return mobileNum;23     }24  25     public String getHomeNum() {26         return homeNum;27     }28 }

布局文件:

 1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3     android:layout_width="match_parent" 4     android:layout_height="match_parent" 5     android:orientation="vertical" > 6  7     <Button 8         android:id="@+id/main_btn" 9         android:layout_width="match_parent"10         android:layout_height="wrap_content"11         android:text="导入联系人" >12     </Button>13         <TextView14             android:id="@+id/main_tv"15             android:layout_width="wrap_content"16             android:layout_height="wrap_content" >17         </TextView>18 19 20 </LinearLayout>

权限:

1    <uses-permission android:name="android.permission.READ_CONTACTS">2    <uses-permission android:name="android.permission.WRITE_CONTACTS">3    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">5  6  7 </uses-permission></uses-permission></uses-permission>

 

转:http://www.2cto.com/kf/201401/272625.html

注:布局文件小改

android 导入数据(通讯录)