本文主要是介绍随Android程序发布SQLite数据库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在发布前我们需要在assets目录下放置我们需要的数据库文件。在Android Studio下默认是没有assets文件夹的,我们需要在/app/src/main/下新建assets文件夹。这里我放置在assets下的数据库名称为test.db
接下来是打开这一文件夹。
新建一个DatabaseHelper
package com.liu.dbhelper;import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;/*** Created by deonte on 15-10-31.*/
public class DataBaseHelper extends SQLiteOpenHelper {private static final String DB_NAME = "test.db"; //数据库名称private static String DBPATH="/data/data/com.liu.dbhelper/databases/";private static final int version = 1; //数据库版本private SQLiteDatabase myDatabase;private Context context;public DataBaseHelper(Context con) {super(con,DB_NAME,null,version);context=con;}@Overridepublic void onCreate(SQLiteDatabase db) {//创建DatabaseHelper}public synchronized void close(){if (myDatabase!=null){myDatabase.close();}super.close();}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}//创建一个空的db,然后替换所选dbpublic void creatDataBase() throws IOException{if (!checkDatabase()){this.getWritableDatabase();try{copyDatabase();}catch (IOException e){Log.i("database--->","Error copying database from assets");}}}//检查数据库是否存在private boolean checkDatabase(){SQLiteDatabase checkableDatabase=null;try{checkableDatabase=SQLiteDatabase.openDatabase(outDBPATH+DB_NAME,null,SQLiteDatabase.OPEN_READONLY);}catch (SQLiteException e){//数据库不存在,返回false}if (checkableDatabase!=null){checkableDatabase.close();}return checkableDatabase!=null?true:false;}//从应用程序资产中复制数据库//越过空使用数据库private void copyDatabase()throws IOException{InputStream myInput=context.getAssets().open(DB_NAME);//打开任一目录下数据库// InputStream myInput=new FileInputStream(DBPATH+DB_NAME);OutputStream myOutput=new FileOutputStream(outDBPATH+DB_NAME);byte[] buffer=new byte[1024];int length;while ((length=myInput.read(buffer))>0){myOutput.write(buffer,0,length);}myOutput.flush();myOutput.close();myInput.close();}public void openDatabase()throws SQLException{myDatabase=SQLiteDatabase.openDatabase(DBPATH+DB_NAME,null,SQLiteDatabase.OPEN_READWRITE);}}
DataBaseHelper dataBaseHelper=new DataBaseHelper(this);try{dataBaseHelper.creatDataBase();}catch (IOException E){Log.i("database---->",E.toString());}
“`
这篇关于随Android程序发布SQLite数据库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!