android 导入数据(通讯录)

本文详细介绍在Android设备上导入联系人的步骤,包括从文本文件读取数据、解析为ContactInfo对象、向系统数据库插入数据及更新UI。代码示例展示了如何处理不同格式的联系人信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

接着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         @Override
126         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相关的handler
138      */
139     private Handler handler = new Handler() {
140         @Override
141         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 enabled
160      */
161     private void setAddWidgetEnabled(boolean enabled) {
162         btn.setEnabled(enabled);
163         if (!enabled) {
164             show.setText("");
165         }
166     }
167  
168     /**
169      * 导入联系人
170      * 
171      * @param context
172      * @param path
173      * @return
174      */
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 path
200      * @return contactsList
201      */
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 strsList
215      * @return
216      */
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 >= 3
241                 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 path
258      * @return
259      */
260     private ArrayList<string> doReadFile(String path) {
261         FileInputStream in = null;
262         ArrayList<string> arrayList = new ArrayList<string>();
263         try {
264             byte[] tempbytes = new