修改你的createDataBase()
方法在你的DatabaseHandler
就像下面的代码:
创建数据库():
public void createDataBase() throws IOException
{
//If database not exists copy it from the assets
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist)
{
this.getReadableDatabase();
this.close();
try
{
//Copy the database from assests
copyDataBase();
System.out.println("createDatabase database created");
}
catch (IOException mIOException)
{
throw new Error("ErrorCopyingDataBase");
}
}
}
检查数据库():
private boolean checkDataBase()
{
File dbFile = new File(DB_PATH + DB_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
复制数据库():
//Copy the database from assets
private void copyDataBase() throws IOException
{
InputStream mInput = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
Where DB_PATH
= /data/data/YOUR_PACKAGE_NAME/Databases/
,您可以在 DatabseHandler 的构造中初始化它,如下所示:DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
DB_NAME
= YOUR_DATABASE_NAME_THAT_IS_STORED_IN_YOUR_ASSETS_FOLDER
我希望这有帮助。
P.S: DB_NAME 和 DB_PATH 都是字符串。
更新 :
每当您尝试使用您的实例时DatabaseHelper
类,调用这个方法就可以了createDatabase()
像这样 :
DatabaseHandler db = new DatabaseHandler(context);
try
{
db.createDataBase();
}
catch (IOException io)
{
throw new Error("Unable to create database");
}
如果数据库尚未复制到数据库目录,它将从资产文件夹复制现有数据库。
我希望这有帮助。