android的数据库存放在/data/data/package name/目录下,所以我们需要把数据库传入到那个目录之下(数据库网上搜后者自己建一个都可以,实在嫌麻烦空的也成 - -)。知道了原理,下面就是编写代码了。
首先在res目录下新建raw目录,将数据库放进去。android会将raw目录中的文件原封不动拷贝到程序中,而不会转换为二进制文件。
创建一个DBOpenHelper类,实现将数据库文件从raw目录中拷贝到手机存放数据库的位置。
下面是代码
public class DBOpenHelper {
private final int BUFFER_SIZE=400000;//缓冲区大小
public static final String DB_NAME="idioms.db";//保存的数据库文件名
public static final String PACKAGE_NAME="com.edu.bztc.happyidiom";//应用的包名
public static final String DB_OATH="/data"
+Environment.getDataDirectory().getAbsolutePath()+"/"
+PACKAGE_NAME+"/databases";//在手机里存放数据库的位置
private Context context;
public DBOpenHelper(Context context) {
this.context=context;
}
public SQLiteDatabase openDatabase(){
Log.i("Database","start");
try {
File myDataPath = new File(DB_OATH);
Log.i("Database",myDataPath.getAbsolutePath());
if (!myDataPath.exists()) {
myDataPath.mkdirs();//没有则创建
}
String dbfile = myDataPath.getAbsolutePath() + "/" + DB_NAME;
/*Log.i("Database",dbfile);
Log.i("Database",(new File(dbfile).exists())+"count");
File[] f = myDataPath.listFiles();
Log.i("file",""+f[0]);
Log.i("file",""+f[1]);
Log.i("file", ""+(new File(f[1].toString()).exists()));*/ 这是数据库出错时用来测试的代码,注释掉就可以
if (!(new File(dbfile).exists())) {//判断数据库文件是否存在,若不存在执行导入,否则直接打开
InputStream is = context.getResources().openRawResource(
R.raw.idioms);
Log.i("Database",is.toString()+"idcount");
FileOutputStream fos=new FileOutputStream(dbfile);
Log.i("Database",fos.toString()+"foscount");
byte[] buffer = new byte[BUFFER_SIZE];
int count = 0;
while ((count = is.read(buffer)) > 0) {
Log.i("Database",count+"count");
fos.write(buffer,0,count);
}
fos.close();
is.close();
}
SQLiteDatabase db=SQLiteDatabase.openOrCreateDatabase(dbfile, null);
Log.i("Database","version"+db.getVersion());
return db;
} catch (Exception e) {
Log.e("Database",""+e);
}
return null;
}
}
然后 修改AndroidManifest.xml文件搭建测试环境
代码如下
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.edu.bztc.happyidiom"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/logo"
android:label="@string/app_name"
android:theme="@android:style/Theme.Holo.Light.NoActionBar" >
<uses-library android:name="android.test.runner"/>
</application>
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.edu.bztc.happyidiom">
</instrumentation>
</manifest>
最后新建DBOpenHelprTest类用于测试
代码如下
public class DBOpenHelprTest extends AndroidTestCase{
public void testDBCopy(){
DBOpenHelper dbOpenHelper=new DBOpenHelper(getContext());
dbOpenHelper.openDatabase();
/*SQLiteDatabase f=dbOpenHelper.openDatabase();
System.out.println(f.getVersion());
*///用于调试错误,注释掉即可
}
}
成功结果