Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android 中導出數據

android 中導出數據

編輯:關於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();
		}
	}
}

布局:



    

權限:

 
 
 




  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved