android 中导出数据

思路很简单:

1、将数据库的数据读取出来,并根据需要作相应处理。

2、将数据写入SD卡

下面以导出系统联系人为例:

MainActivity:

package com.home.exportcontact;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
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;

public class MainActivity extends Activity implements OnClickListener {
	private Button exportBtn;// 导出按钮
	private TextView showText;// 显示进度的文本
	// 导出txt的存放位置
	private final static String OUTPUT_PATH = Environment
			.getExternalStorageDirectory() + "/我的联系人.txt";
	private static final int OUTPUT_FAIL = 0;// 导出失败标识
	private static final int OUTPUT_SUCCESS = 1;// 导出成功标识
	private static int count;// 导出联系人的计数
	private Thread mOutputThread;// 导出联系人线程
	// 空格
	private static final String SPACE_1 = " ";
	private static final String SPACE_2 = SPACE_1 + SPACE_1;
	private static final String SPACE_4 = SPACE_2 + SPACE_2;
	private static final String SPACE_8 = SPACE_4 + SPACE_4;
	private static final String SPACE_11 = SPACE_8 + SPACE_2 + SPACE_1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		exportBtn = (Button) findViewById(R.id.main_btn_export);
		exportBtn.setOnClickListener(this);
		showText = (TextView) findViewById(R.id.main_tv_show);
	}

	@Override
	public void onClick(View v) {
		if (v == exportBtn) {
			outputContact();
		}
	}

	/**
	 * 导出联系人入口
	 */
	private void outputContact() {
		File file = new File(OUTPUT_PATH);
		if (!file.exists()) {
			startOutputContact();
		} else {
			createDialog(this, "警告", "我的联系人.txt已经存在,是否覆盖?");
		}
	}

	/**
	 * 创建提示对话框
	 * 
	 * @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) {
				startOutputContact();
			}
		});
		builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
			}
		});
		builder.show();
	}

	/**
	 * 开启导出联系人子线程
	 */
	private void startOutputContact() {
		setOutputWidgetEnabled(false);
		showText.setText("正在导出联系人...");
		if (mOutputThread != null) {
			mOutputThread.interrupt();
			mOutputThread = null;
		}
		mOutputThread = new Thread(new OutputRunnable(this));
		if (mOutputThread != null) {
			mOutputThread.start();
		}
	}

	/**
	 * 设置导出组件的可用性
	 */
	private void setOutputWidgetEnabled(boolean enabled) {
		exportBtn.setEnabled(enabled);
		if (!enabled) {
			showText.setText("");
		}
	}

	class OutputRunnable implements Runnable {
		private Context context;

		public OutputRunnable(Context context) {
			this.context = context;
		}

		@Override
		public void run() {
			boolean result = doOutputContact(context);
			if (result) {
				handler.sendEmptyMessage(OUTPUT_SUCCESS);
			} else {
				handler.sendEmptyMessage(OUTPUT_FAIL);
			}
		}
	}

	/**
	 * 处理UI提示相关
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == OUTPUT_SUCCESS) {
				showText.setText((String.format("已成功导出 %d 条联系人记录", count)));
				setOutputWidgetEnabled(true);
			} else if (msg.what == OUTPUT_FAIL) {
				showText.setText("导入联系人失败");
				setOutputWidgetEnabled(true);
			}
		}
	};

	/**
	 * 从数据库中导出联系人
	 * 
	 * @param context
	 * @return 是否成功
	 */
	private boolean doOutputContact(Context context) {
		count = 0;
		try {
			String result = readFromContactDatabase(context);
			writeFile(OUTPUT_PATH, result);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 从数据库中读取联系人相关信息
	 * 
	 * @param context
	 * @return 信息结果
	 */
	private String readFromContactDatabase(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);
		while (cursor.moveToNext()) {
			// 得到名称和每一行记录的ID
			String displayName = cursor.getString(0);
			int id = cursor.getInt(1);
			// 得到电话号码的游标
			Cursor mobileCursor = context.getContentResolver().query(
					ContactsContract.Data.CONTENT_URI,
					new String[] { Phone.NUMBER },
					Data.RAW_CONTACT_ID + " = " + id + " AND " + Data.DATA2
							+ " = " + 2, null, null);
			String mobileNum = "";
			if (mobileCursor.moveToNext()) {
				mobileNum = mobileCursor.getString(0);
			}
			mobileCursor.close();
			// 得到家庭电话
			Cursor homeCursor = context.getContentResolver().query(
					ContactsContract.Data.CONTENT_URI,
					new String[] { Phone.NUMBER },
					Data.RAW_CONTACT_ID + " = " + id + " AND " + Data.DATA2
							+ " = " + 1, null, null);
			String homeNum = "";
			if (homeCursor.moveToNext()) {
				homeNum = homeCursor.getString(0);
			}
			homeCursor.close();
			if (displayName != null && !"".equals(displayName)) {
				String result = displayName + SPACE_4;
				if ("".equals(mobileNum)) {
					result += SPACE_11;
				} else {
					result += mobileNum;
				}
				result += SPACE_8 + homeNum + ‘\n‘;
				String checkString = resultBuilder.toString();
				if (!checkString.contains(result)
						&& ("".equals(mobileNum) || !checkString
								.contains(mobileNum))) {
					resultBuilder.append(result);
					count++;
				}
			}
		}
		cursor.close();
		return resultBuilder.toString();
	}

	/**
	 * 将联系人信息写入SD
	 * 
	 * @param path
	 * @param info
	 */
	private void writeFile(String path, String info) {
		try {
			File file = new File(path);
			FileWriter writer = new FileWriter(file, false);
			writer.write(info);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

布局:

<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_export"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="导出联系人" />

    <TextView
        android:id="@+id/main_tv_show"
        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" />




 

android 中导出数据

上一篇:Photoshop调色教程唯美风格的照片


下一篇:【android浅析】android程序界面编程与视图(View)组件