ITEEDU

DataBaseHelper将sqlite数据库打包进apk

package com.iteedu.www;

import java.io.*;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.*;


public class DataBaseHelper{

	// The Android's default system path of your application database.
	private static String DATABASE_PATH = "/data/data/com.iteedu.www/databases/";
	private static String DATABASE_FILENAME = "wordroot.db";
	public SQLiteDatabase myDataBase;
	private final Context myContext;

	public DataBaseHelper(Context context) {
		
		this.myContext = context;
	}
	public void openDataBase() throws SQLException {

		// Open the database
		String databaseFilename = DATABASE_PATH + DATABASE_FILENAME;
		myDataBase = SQLiteDatabase.openDatabase(databaseFilename, null,
				SQLiteDatabase.OPEN_READONLY);
	}
	public void createDataBase() throws IOException {

		boolean dbExist = checkDataBase();

		if (dbExist) {

			// do nothing - database already exist

		} else {
			//this.getReadableDatabase();
			try {
				copyDataBase();
			} catch (IOException e) {
			
				throw new Error("Error copying database");
			}
		}
	}

	private boolean checkDataBase() {

		SQLiteDatabase checkDB = null;

		try {

			String databaseFilename = DATABASE_PATH + DATABASE_FILENAME;

			checkDB = SQLiteDatabase.openDatabase(databaseFilename, null,
					SQLiteDatabase.OPEN_READONLY);

		} catch (SQLiteException e) {
			// database does't exist yet.
		}

		if (checkDB != null) {
			checkDB.close();
		}

		return checkDB != null ? true : false;
	}

	private void copyDataBase() throws IOException {

		String databaseFilename = DATABASE_PATH + DATABASE_FILENAME;
		File dir = new File(DATABASE_PATH);
		
		if (!dir.exists())
			dir.mkdir();

		FileOutputStream os = null;
		try {

			os = new FileOutputStream(databaseFilename);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		InputStream is = myContext.getResources().openRawResource(R.raw.wordroot);
		byte[] buffer = new byte[8192];
		int count = 0;
		// 开始复制db文件
		try {
			while ((count = is.read(buffer)) > 0) {
				os.write(buffer, 0, count);
				os.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			is.close();
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}