Android导入导出txt通讯录工具(源码共享)
16lz
2021-01-26
续http://blog.csdn.net/zyc13701469860/article/details/7217836
在这里给出我的源代码,也可以从 http://download.csdn.net/detail/zyc13701469860/4034404下载
设计思路比较简单,实际操作也就是读写文件和数据库
导入:
1.从txt文档中解析出相应的信息
2.将信息插入联系人表对应的列
导入代码
package com.zyc.contact.tool;import java.io.FileInputStream;import java.io.IOException;import java.util.ArrayList;import java.util.Iterator;import android.content.ContentUris;import android.content.ContentValues;import android.content.Context;import android.net.Uri;import android.provider.ContactsContract;import android.provider.ContactsContract.CommonDataKinds.Phone;import android.provider.ContactsContract.CommonDataKinds.StructuredName;import android.provider.ContactsContract.Contacts.Data;import android.provider.ContactsContract.RawContacts;import android.util.Log;public class ContactToolInsertUtils extends ContactToolUtils{private static final String TAG = "ContactToolInsertUtils";private static int successCount = 0;private static int failCount = 0;private static boolean isGbk = false;public static boolean insertIntoContact(Context context,String path,String charset){init(charset);try{ArrayList arrayList = readFromFile(path);if(arrayList == null){Log.e(TAG, "Error in insertIntoContact arrayList == null");return false;}Iterator iterator = arrayList.iterator();while(iterator.hasNext()){ContactInfo contactInfo = iterator.next();if(doInsertIntoContact(context,contactInfo)){successCount++;}}}catch (Exception e) {Log.e(TAG, "Error in insertIntoContact result : " + e.getMessage());}return true;}private static void init(String charset){successCount = 0;failCount =0;isGbk = charset.equals(ContactContant.CHARSET_GBK);}/**read txt file*/private static ArrayList readFromFile(String path){//read from fileArrayList stringsArrayList = doReadFile(path);if(stringsArrayList == null){Log.e(TAG, "Error in readFromFile stringsArrayList == null");return null;}ArrayList contactInfoArrayList = handleReadStrings(stringsArrayList);return contactInfoArrayList;}private static ArrayList doReadFile(String path){FileInputStream in = null;ArrayList arrayList = new ArrayList(); try { byte[] tempbytes = new byte[ContactContant.BUFFER_SIZE]; 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] == ContactContant.ENTER_CHAR_LINUX){ length = i; byte[] nowBytes = new byte[length - first]; System.arraycopy(tempbytes, first, nowBytes, 0, length - first); if(isGbk){ arrayList.add(new String(nowBytes,ContactContant.CHARSET_GBK).trim()); } else { arrayList.add(new String(nowBytes,ContactContant.CHARSET_UTF8).trim());} first = i + 1; } } } } catch (Exception e1) { return null; } finally { if (in != null) { try { in.close(); } catch (IOException e1) { return null; } } } return arrayList;}private static ArrayList handleReadStrings(ArrayList arrayList){ArrayList contactInfoArrayList = new ArrayList();Iterator infos = arrayList.iterator();while(infos.hasNext()){String info = infos.next();String[] infoStrings = info.split(ContactContant.SPACE_REGULAR);String displayName = null;String mobileNum = null;String homeNum = null;switch (infoStrings.length) {case 0://do nothingcontinue;case 1:displayName = infoStrings[0];break;case 2:displayName = infoStrings[0];if(infoStrings[1].length() == ContactContant.MOBILE_NUM_LENGTH){mobileNum = infoStrings[1];}else{homeNum = infoStrings[1];}break;default://length >= 3displayName = infoStrings[0];mobileNum = infoStrings[1];homeNum = infoStrings[2];}//check displayName mobileNum and homeNumif(displayName == null || displayName.matches(ContactContant.NUM_REGULAR)){Log.e(TAG, "Error in handleReadStrings displayName == null");failCount++;continue;}if(mobileNum != null && (mobileNum.length() != ContactContant.MOBILE_NUM_LENGTH || !mobileNum.matches(ContactContant.NUM_REGULAR))){Log.e(TAG, "Error in handleReadStrings mobileNum is not all num or mobileNum == null");failCount++;continue;}if(homeNum != null && !(homeNum.matches(ContactContant.HOME_REGULAR_01) || homeNum.matches(ContactContant.HOME_REGULAR_02))){Log.e(TAG, "Error in handleReadStrings homeNum is not all num");failCount++;continue;}contactInfoArrayList.add(new ContactInfo(displayName, mobileNum, homeNum));}return contactInfoArrayList;}/**insert into database*/private static boolean doInsertIntoContact(Context context,ContactInfo contactInfo){Log.d(TAG, "in doInsertIntoContact contactInfo = null? " + (contactInfo == null));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(); //insert name 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; //check name if english 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){ //insert phone 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){ //insert houseNum 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; }private static 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;}public static int getSuccessCount() {return successCount;}public static int getFailCount() {return failCount;}}
导出:
1.从联系人表中获取相应的信息
2.将信息输出成txt文件
package com.zyc.contact.tool;import java.io.File;import java.io.FileWriter;import java.io.IOException;import android.content.Context;import android.database.Cursor;import android.provider.ContactsContract;import android.provider.ContactsContract.CommonDataKinds.Phone;import android.provider.ContactsContract.CommonDataKinds.StructuredName;import android.provider.ContactsContract.Contacts.Data;import android.util.Log;public class ContactToolOutputUtils extends ContactToolUtils {private static final String TAG = "ContactOutputTool";private static int mCount = 0;public static boolean outputContacts(Context context) {init();try {String result = getFromContactDatabase(context);writeFile(ContactContant.OUTPUT_PATH, result);} catch (Exception e) {Log.e(TAG, "Error in outputContacts " + e.getMessage());return false;}return true;}private static void init() {mCount = 0;}private static String getFromContactDatabase(Context context) {StringBuilder resultBuilder = new StringBuilder();Cursor cursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,new String[] { StructuredName.DISPLAY_NAME,Data.RAW_CONTACT_ID }, Data.MIMETYPE + "= ?",new String[] { StructuredName.CONTENT_ITEM_TYPE }, null);cursor.moveToFirst();while (!cursor.isAfterLast()) {// get display name and row idString displayName = cursor.getString(0);int id = cursor.getInt(1);// get phone numCursor mobileCursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,new String[] { Phone.NUMBER },Data.RAW_CONTACT_ID + " = " + id + " AND " + Data.DATA2+ " = " + ContactContant.MOBILE_ID, null, null);String mobileNum = ContactContant.NO_TEXT;mobileCursor.moveToFirst();if (!mobileCursor.isAfterLast()) {mobileNum = mobileCursor.getString(0);}mobileCursor.close();// get home numCursor homeCursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,new String[] { Phone.NUMBER },Data.RAW_CONTACT_ID + " = " + id + " AND " + Data.DATA2+ " = " + ContactContant.HOME_ID, null, null);String homeNum = ContactContant.NO_TEXT;homeCursor.moveToFirst();if (!homeCursor.isAfterLast()) {homeNum = homeCursor.getString(0);}homeCursor.close();if (displayName != null && (!displayName.equals(ContactContant.NO_TEXT) || !displayName.equals(ContactContant.NULL_TEXT))) {String result = displayName + ContactContant.SPACE_STRING_4;if(mobileNum.equals(ContactContant.NO_TEXT)){result += ContactContant.NO_MOBILE_NUM;}else {result += mobileNum;}result += ContactContant.SPACE_STRING_8 + homeNum;result += ContactContant.ENTER_CHAR_LINUX;String checkString = resultBuilder.toString();if(!checkString.contains(result) && (mobileNum.equals(ContactContant.NO_TEXT) ||!checkString.contains(mobileNum))){resultBuilder.append(result);mCount++;}}cursor.moveToNext();}cursor.close();return resultBuilder.toString();}private static void writeFile(String path, String buffer) {try {File file = new File(path);FileWriter writer = new FileWriter(file, false);writer.write(buffer);writer.close();} catch (IOException e) {e.printStackTrace();}}public static int getCount(){return mCount;}}
控制流程及UI显示
package com.zyc.contact.tool;import java.io.File;import android.app.Activity;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.RadioButton;import android.widget.TextView;public class ContactToolActivity extends Activity implements OnClickListener {private EditText mEditText;private Button mHelpButton;private Button mInsertButton;private Button mOutputButton;private TextView mResultTextView;private TextView mOsTextView;private RadioButton[] mOsSetButtons = new RadioButton[2];private RadioButton[] mModeButtons = new RadioButton[2];private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case ContactContant.INSERT_FAIL:mResultTextView.setText(ContactContant.FAIL_INSERT);endInsertContact();break;case ContactContant.INSERT_SUCCESS:mResultTextView.setText(String.format(ContactContant.SUCCESS_INSERT,ContactToolInsertUtils.getSuccessCount(),ContactToolInsertUtils.getFailCount()));endInsertContact();break;case ContactContant.OUTPUT_FAIL:mResultTextView.setText(ContactContant.FAIL_OUTPUT);endOutputContact();break;case ContactContant.OUTPUT_SUCCESS:mResultTextView.setText((String.format(ContactContant.SUCCESS_OUTPUT,ContactToolOutputUtils.getCount())));endOutputContact();break;}}};@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);init();}/*init widgets*/private void init() {mEditText = (EditText) findViewById(R.id.edit_text);mHelpButton = (Button) findViewById(R.id.help_button);mHelpButton.setOnClickListener(this);mInsertButton = (Button) findViewById(R.id.insert_button);mInsertButton.setOnClickListener(this);mOutputButton = (Button) findViewById(R.id.output_button);mOutputButton.setOnClickListener(this);mResultTextView = (TextView) findViewById(R.id.result_view);mOsTextView = (TextView)findViewById(R.id.os_text);mOsSetButtons[0] = (RadioButton) findViewById(R.id.radio_button_win);// set gbk defaultmOsSetButtons[0].setChecked(true);mOsSetButtons[1] = (RadioButton) findViewById(R.id.radio_button_linux);mModeButtons[0] = (RadioButton) findViewById(R.id.radio_insert);mModeButtons[0].setOnClickListener(this);mModeButtons[1] = (RadioButton) findViewById(R.id.radio_output);mModeButtons[1].setOnClickListener(this);setInsertWidgetEnabled(false);setOutputWidgetEnabled(false);}@Overridepublic void onResume() {super.onResume();}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.help_button:createDialog(this,ContactContant.HELP_DIALOG_TITLE,ContactContant.HELP_MESSAGE,false,ContactContant.DIALOG_TYPE_HELP);break;case R.id.insert_button:insertContact();break;case R.id.output_button:outputContact();break;case R.id.radio_insert:setOutputWidgetEnabled(false);setInsertWidgetEnabled(true);break;case R.id.radio_output:setInsertWidgetEnabled(false);setOutputWidgetEnabled(true);break;}}public void createDialog(Context context, String title, String message,boolean hasCancel, final int type) {AlertDialog.Builder builder = new AlertDialog.Builder(context);builder.setTitle(title);builder.setMessage(message);builder.setPositiveButton(ContactContant.DIALOG_OK,new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int whichButton) {switch (type) {case ContactContant.DIALOG_TYPE_HELP:dialog.cancel();break;case ContactContant.DIALOG_TYPE_INSERT:doInsertContact();break;case ContactContant.DIALOG_TYPE_OUTPUT:doOutputContact();break;}}});if (hasCancel) {builder.setNeutralButton(ContactContant.DIALOG_CANCEL,new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int whichButton) {dialog.cancel();}});}builder.show();}private void setInsertWidgetEnabled(boolean enable) {mOsSetButtons[0].setEnabled(enable);mOsSetButtons[1].setEnabled(enable);mInsertButton.setEnabled(enable);mEditText.setEnabled(enable);int visable = enable ? View.VISIBLE : View.INVISIBLE;mOsSetButtons[0].setVisibility(visable);mOsSetButtons[1].setVisibility(visable);mOsTextView.setVisibility(visable);if(!enable){mResultTextView.setText(ContactContant.NO_TEXT);}}private void insertContact() {String path = mEditText.getText().toString();if (path == null || path.equals(ContactContant.NO_TEXT)) {ContactToolUtils.showToast(this,ContactContant.FAIL_EDITTEXT_NOT_INPUT);mResultTextView.setText(ContactContant.FAIL_EDITTEXT_NOT_INPUT);return;}path = ContactContant.FILE_NAME_PARENT + path;if (!new File(path).exists()) {ContactToolUtils.showToast(this, ContactContant.FAIL_FIRE_NOT_EXIST);mResultTextView.setText(ContactContant.FAIL_FIRE_NOT_EXIST);return;}if (mInsertThread != null) {mInsertThread.interrupt();mInsertThread = null;}String charset = mOsSetButtons[0].isChecked() ? ContactContant.CHARSET_GBK: ContactContant.CHARSET_UTF8;mInsertThread = new Thread(new InsertRunnable(this, path, charset));createDialog(this, ContactContant.WARNDIALOG_TITLE,ContactContant.INSERT_WARNDIALOG_MESSAGE, true,ContactContant.DIALOG_TYPE_INSERT);}private void doInsertContact() {setInsertWidgetEnabled(false);mResultTextView.setText(ContactContant.STATUS_INSERTING);if (mInsertThread != null) {mInsertThread.start();}}private void endInsertContact() {mEditText.setText(ContactContant.NO_TEXT);setInsertWidgetEnabled(true);}private Thread mInsertThread;class InsertRunnable implements Runnable {private Context mContext;private String mPath;private String mCharset;public InsertRunnable(Context context, String path, String charset) {mPath = path;mContext = context;mCharset = charset;}@Overridepublic void run() {boolean result = ContactToolInsertUtils.insertIntoContact(mContext,mPath, mCharset);if (result) {mHandler.sendEmptyMessage(ContactContant.INSERT_SUCCESS);} else {mHandler.sendEmptyMessage(ContactContant.INSERT_FAIL);}}}private void setOutputWidgetEnabled(boolean enable) {mOutputButton.setEnabled(enable);if(!enable){mResultTextView.setText(ContactContant.NO_TEXT);}}private void outputContact(){File file = new File(ContactContant.OUTPUT_PATH);if(file.exists()){createDialog(this, ContactContant.WARNDIALOG_TITLE,ContactContant.OUTPUT_WARNDIALOG_MESSAGE, true,ContactContant.DIALOG_TYPE_OUTPUT);}else {doOutputContact();}}private void doOutputContact(){setOutputWidgetEnabled(false);mResultTextView.setText(ContactContant.STATUS_OUTPUTING);if (mOutputThread != null) {mOutputThread.interrupt();mOutputThread = null;}mOutputThread = new Thread(new OutputRunnable(this));if (mOutputThread != null) {mOutputThread.start();}}private Thread mOutputThread;class OutputRunnable implements Runnable {private Context mContext;public OutputRunnable(Context context) {mContext = context;}@Overridepublic void run() {boolean result = ContactToolOutputUtils.outputContacts(mContext);if (result) {mHandler.sendEmptyMessage(ContactContant.OUTPUT_SUCCESS);} else {mHandler.sendEmptyMessage(ContactContant.OUTPUT_FAIL);}}}private void endOutputContact() {setOutputWidgetEnabled(true);}}
常量类和联系人信息类的代码这里就不贴了。
更多相关文章
- Android(安卓)gradle打包并自动上传
- android中WebView的Java与JavaScript交互
- 防止屏幕锁屏
- 《第一行代码》 6.3 SharedPreferences存储
- Android(java)同步方法synchronized
- (转)Android(安卓)Studio插件整理
- 使用PreferenceActivity设置应用程序参数
- Content Provider使用方法以及Android运行时权限申请
- 一行代码完成Android(安卓)7 FileProvider适配~