接着android 中导出数据 一文,下面介绍在android中导入数据的思路:
1、将数据从文本中读取出来
2、封装处理成自己想要的对象或模型
3、将处理好的数据对象插入自己应用的数据库中
4、更新UI显示
下面仍以导入联系人至系统中为例,若是导入自己的应用中,思路一样甚至更简单,代码如下:
注:我的联系人.txt的格式即为android 中导出数据 一文生成的格式
MainActivity:
package com.home.impcontact; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.ContactsContract; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.Contacts.Data; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { private Button btn;// 导入按钮 private TextView show;// 显示结果的文本框 private Thread addThread;// 增加联系人线程 private static final int ADD_FAIL = 0;// 导入失败标识 private static final int ADD_SUCCESS = 1;// 导入成功标识 private static int successCount = 0;// 导入成功的计数 private static int failCount = 0;// 导入失败的计数 // 默认文件路劲,实际情况应作相应修改或从界面输入或浏览选择 private static final String PATH = Environment .getExternalStorageDirectory() + "/我的联系人.txt"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } /** * 初始化组件 */ private void init() { btn = (Button) findViewById(R.id.main_btn); btn.setOnClickListener(this); show = (TextView) findViewById(R.id.main_tv); } @Override public void onClick(View v) { if (v == btn) { addContact(); } } /** * 导入联系人入口 */ private void addContact() { if (!new File(PATH).exists()) { Toast.makeText(this, "文件不存在!", Toast.LENGTH_SHORT).show(); show.setText("文件不存在!"); return; } if (addThread != null) { addThread.interrupt(); addThread = null; } addThread = new Thread(new AddRunnable(this, PATH)); createDialog(this, "警告", "确保你是第一次导入,重复导入会创建新的联系人,请慎用!"); } /** * 创建提示对话框 * * @param context * @param title * @param message */ private void createDialog(Context context, String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(title); builder.setMessage(message); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { startAddContact(); } }); builder.setNeutralButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); builder.show(); } /** * 开启导入线程 */ private void startAddContact() { setAddWidgetEnabled(false); show.setText("正在导入联系人..."); if (addThread != null) { addThread.start(); } } class AddRunnable implements Runnable { private Context context; private String path; public AddRunnable(Context context, String path) { this.path = path; this.context = context; } @Override public void run() { boolean result = importContact(context, path); if (result) { handler.sendEmptyMessage(ADD_SUCCESS); } else { handler.sendEmptyMessage(ADD_FAIL); } } } /** * 处理UI相关的handler */ private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case ADD_FAIL: show.setText("导入联系人失败"); setAddWidgetEnabled(true); break; case ADD_SUCCESS: show.setText(String.format("导入联系人成功 %d 条,失败 %d 条", successCount, failCount)); setAddWidgetEnabled(true); break; } } }; /** * 设置导入组件的可用性 * * @param enabled */ private void setAddWidgetEnabled(boolean enabled) { btn.setEnabled(enabled); if (!enabled) { show.setText(""); } } /** * 导入联系人 * * @param context * @param path * @return */ private boolean importContact(Context context, String path) { successCount = 0; failCount = 0; try { ArrayList<ContactInfo> list = readFromFile(path); if (list == null) { return false; } for (int i = 0; i < list.size(); i++) { ContactInfo info = list.get(i); if (doAddContact(context, info)) { successCount++; } } } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * 读取联系人并封装成ContactInfo对象集合 * * @param path * @return contactsList */ private ArrayList<ContactInfo> readFromFile(String path) { ArrayList<String> strsList = doReadFile(path); if (strsList == null) { return null; } ArrayList<ContactInfo> contactsList = handleReadStrs(strsList); return contactsList; } /** * 将读出来的内容封装成ContactInfo对象集合 * * @param strsList * @return */ private ArrayList<ContactInfo> handleReadStrs(ArrayList<String> strsList) { ArrayList<ContactInfo> contactsList = new ArrayList<ContactInfo>(); for (int i = 0; i < strsList.size(); i++) { String info = strsList.get(i); String[] infos = info.split("\\s{2,}"); String displayName = null; String mobileNum = null; String homeNum = null; switch (infos.length) { case 0: continue; case 1: displayName = infos[0]; break; case 2: displayName = infos[0]; if (infos[1].length() >= 11) { mobileNum = infos[1]; } else { homeNum = infos[1]; } break; default: // length >= 3 displayName = infos[0]; mobileNum = infos[1]; homeNum = infos[2]; } if (displayName == null || "".equals(displayName)) { failCount++; continue; } contactsList.add(new ContactInfo(displayName, mobileNum, homeNum)); } return contactsList; } /** * 读取文件内容 * * @param path * @return */ private ArrayList<String> doReadFile(String path) { FileInputStream in = null; ArrayList<String> arrayList = new ArrayList<String>(); try { byte[] tempbytes = new byte[1 << 24]; in = new FileInputStream(path); while (in.read(tempbytes) != -1) { int length = 0; int first = length; for (int i = 0; i < tempbytes.length; i++) { if (tempbytes[i] == ‘\n‘) { length = i; byte[] nowBytes = new byte[length - first]; System.arraycopy(tempbytes, first, nowBytes, 0, length - first); arrayList.add(new String(nowBytes, "utf-8").trim()); first = i + 1; } } } } catch (Exception e1) { return null; } finally { if (in != null) { try { in.close(); } catch (IOException e1) { return null; } } } return arrayList; } /** * 向数据库表插入联系人信息 * * @param context * @param contactInfo * @return */ private boolean doAddContact(Context context, ContactInfo contactInfo) { try { ContentValues contentValues = new ContentValues(); Uri uri = context.getContentResolver().insert( RawContacts.CONTENT_URI, contentValues); long rowId = ContentUris.parseId(uri); String name = contactInfo.getDisplayName(); String mobileNum = contactInfo.getMobileNum(); String homeNum = contactInfo.getHomeNum(); // 插入姓名 if (name != null) { contentValues.clear(); contentValues.put(Data.RAW_CONTACT_ID, rowId); contentValues.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); int index = name.length() / 2; String displayName = name; String givenName = null; String familyName = null; // 检查是否是英文名称 if (checkEnglishName(displayName) == false) { givenName = name.substring(index); familyName = name.substring(0, index); } else { givenName = familyName = displayName; } contentValues.put(StructuredName.DISPLAY_NAME, displayName); contentValues.put(StructuredName.GIVEN_NAME, givenName); contentValues.put(StructuredName.FAMILY_NAME, familyName); context.getContentResolver().insert( ContactsContract.Data.CONTENT_URI, contentValues); } if (mobileNum != null) { // 插入手机电话 contentValues.clear(); contentValues.put(Data.RAW_CONTACT_ID, rowId); contentValues.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); contentValues.put(Phone.NUMBER, mobileNum); contentValues.put(Phone.TYPE, Phone.TYPE_MOBILE); context.getContentResolver().insert( ContactsContract.Data.CONTENT_URI, contentValues); } if (homeNum != null) { // 插入家庭号码 contentValues.clear(); contentValues.put(Data.RAW_CONTACT_ID, rowId); contentValues.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE); contentValues.put(Phone.NUMBER, homeNum); contentValues.put(Phone.TYPE, Phone.TYPE_HOME); context.getContentResolver().insert( ContactsContract.Data.CONTENT_URI, contentValues); } } catch (Exception e) { return false; } return true; } /** * 检查是否是英文名称 * * @param name * @return */ private boolean checkEnglishName(String name) { char[] nameChars = name.toCharArray(); for (int i = 0; i < nameChars.length; i++) { if ((nameChars[i] >= ‘a‘ && nameChars[i] <= ‘z‘) || (nameChars[i] >= ‘A‘ && nameChars[i] <= ‘Z‘)) { continue; } return false; } return true; } }
联系人实体类ContactInfo:
package com.home.impcontact; public class ContactInfo { /** 名称 */ private String displayName; /** 手机号 */ private String mobileNum; /** 家庭电话 */ private String homeNum; public ContactInfo(String displayName, String mobileNum, String homeNum) { this.displayName = displayName; this.mobileNum = mobileNum; this.homeNum = homeNum; } public String getDisplayName() { return displayName; } public String getMobileNum() { return mobileNum; } public String getHomeNum() { return homeNum; } }
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/main_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="导入联系人" /> <TextView android:id="@+id/main_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
权限:
<uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />