我的数据库出了问题。 应用程序启动时,资产会自动加载数据库。 只有在它不存在的情况下才应加载(首次启动应用程序),但它不起作用。
这是我的代码:
public static boolean copyDBFile(Context context)
{
File dbAbsolutePathFile = new File(dbPath + dbName);
File dbPathFile = new File(dbPath);
//Here we make sure that the directory path for the database exists
if(!dbPathFile.exists()) {
dbPathFile.mkdirs();
}
File dbNameFile = context.getDatabasePath(dbName);
//Here we check whether the database file exists or not. If not, we then create it
if(!dbNameFile.exists()) {
Log.d("database", "copy");
//dbNameFile = new File(dbName);
try {
//Here we call the copyDB() method.
copyDB(context.getAssets().open(dbName), new FileOutputStream(dbPath + dbName));
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
return true;
}
private static void copyDB(InputStream inputStream, OutputStream outputStream) {
byte[] buffer = new byte[1024];
int length;
//Here we copy 1K bytes at a time
try {
while((length=inputStream.read(buffer))>0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
} catch (IOException e) {
}
}
答案 0 :(得分:1)
试试此代码
public class MyApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
if(! MyDBHelper.isDatabaseExist(Your_Context , YOUR_DATABASE_NAME))
new MyDBHelper(this).ImportDatabase(this);
}
}
public static boolean isDatabaseExist(ContextWrapper context, String dbName)
{
File dbFile = context.getDatabasePath(dbName);
return dbFile.exists();
}
用于导入数据库
public Boolean ImportDatabase(Context c)
{
InputStream myInput = null;
try {
myInput = c.getAssets().open("Assets/Database.db");
// Set the output file stream up:
SQLiteDatabase db = getReadableDatabase();
OutputStream myOutput = new FileOutputStream(db.getPath());
db.close();
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0)
{
myOutput.write(buffer, 0, length);
}
// Close and clear the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
catch (FileNotFoundException e)
{
Log.e("Restoring Database", "file not found");
e.printStackTrace();
return false;
}
catch (IOException e)
{
Log.e("Restoring Database", "IO exception");
e.printStackTrace();
return false;
}
Log.e("Restoring Database", "Restored");
return true;
}