1

我是android开发的新手。现在我正在尝试使用 sqlite db。我使用 sqlite manager 创建了一个数据库 sqlite 文件。我已经尝试了以下代码,它在模拟器中运行良好,但是如果我在设备中发布应用程序崩溃,即,它会显示一条警报消息应用程序 CheckMobileForDatabase 已意外停止,我的 sdk 版本是 2.2(8)

 private void StoreDatabase() {
 File DbFile=new File("data/data/com.sqldemo/databases/idua1");
 if(DbFile.exists())
 {
     System.out.println("file already exist ,No need to Create");
 }
 else
 {
     try 
     {
         DbFile.createNewFile();
         System.out.println("File Created successfully");
         InputStream is = this.getAssets().open("idua1.sqlite");
         FileOutputStream fos = new FileOutputStream(DbFile);
         byte[] buffer = new byte[1024];
            int length=0;
            while ((length = is.read(buffer))>0)
            {
            fos.write(buffer, 0, length);
            }
         System.out.println("File succesfully placed on sdcard");
            //Close the streams
            fos.flush();
            fos.close();
            is.close();
     }
     catch (IOException e)
     {
         e.printStackTrace();
     }
   }    
   }
4

2 回答 2

1

这可能是由于存储在您的 android 设备中的以前版本的数据库,尝试从您的设备中删除以前的数据库或更改代码中的数据库版本,以便调用 onupgrade

于 2012-05-23T14:37:46.560 回答
0

没有你的 logcat,这只是在黑暗中拍摄。

您可以尝试以另一种方式检查文件是否存在:

private static boolean checkDataBase(String dbname) {
    SQLiteDatabase checkDB = null;
    boolean exist = false;
    try {
        String db = MAIN_DB_PATH + dbname;
        checkDB = SQLiteDatabase.openDatabase(db, null,
                SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
        Log.v("db log", "database does't exist");
    }
    if (checkDB != null) {
        exist = true;
        checkDB.close();
    }
    return exist;
}

如果它不存在,然后运行另一种方法来复制数据库:

private static void copyDataBase(String dbname) throws IOException {
    InputStream myInput = mCtx.getAssets().open(dbname);
    String outFileName = MAIN_DB_PATH + dbname;
    OutputStream myOutput = new FileOutputStream(outFileName);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }
    myOutput.flush();
    myOutput.close();
    myInput.close();
}
于 2012-05-23T15:31:28.323 回答