Android导入导出txt通讯录工具(源码共享)

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<ContactInfo> arrayList = readFromFile(path);
			if(arrayList == null){
				Log.e(TAG, "Error in insertIntoContact arrayList == null");
				return false;
			}
			Iterator<ContactInfo> 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<ContactInfo> readFromFile(String path){
		//read from file
		ArrayList<String> stringsArrayList = doReadFile(path);
		if(stringsArrayList == null){
			Log.e(TAG, "Error in readFromFile stringsArrayList == null");
			return null;
		}
		ArrayList<ContactInfo> contactInfoArrayList = handleReadStrings(stringsArrayList);
		return contactInfoArrayList;
	}
	
	private static ArrayList<String> doReadFile(String path){
		FileInputStream in = null;	
		ArrayList<String> arrayList = new ArrayList<String>();
	    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<ContactInfo> handleReadStrings(ArrayList<String> arrayList){
		ArrayList<ContactInfo> contactInfoArrayList = new ArrayList<ContactInfo>();
		Iterator<String> 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 nothing
				continue;
			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 >= 3
				displayName = infoStrings[0];
				mobileNum = infoStrings[1];
				homeNum = infoStrings[2];
			}
			//check displayName mobileNum and homeNum
			if(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 id
			String displayName = cursor.getString(0);
			int id = cursor.getInt(1);
			
			// get phone num
			Cursor 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 num
			Cursor 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() {
		@Override
		public 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;
			}
		}
	};

	@Override
	public 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 default
		mOsSetButtons[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);
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public 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;
		}

		@Override
		public 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;
		}

		@Override
		public 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);
	}
}

常量类和联系人信息类的代码这里就不贴了。



评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值