【问题标题】:Issues in import database in androidandroid中导入数据库的问题
【发布时间】:2012-05-30 03:08:57
【问题描述】:

我是安卓开发新手。现在我正在尝试使用 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();
     }
   }    
   }

【问题讨论】:

  • 请发布显示错误的logcat。
  • 以上代码在模拟器中工作正常,但我发布该项目它在模拟器中工作正常,应用程序崩溃,它显示警告消息应用程序 CheckMobileForDatabase 已意外停止。请解决此问题
  • 所以在手机插入的情况下运行它,然后在它崩溃时抓住 logcat 并发布它。我们不能做任何事情而不知道它失败的为什么,因为您发布的代码中没有任何明显的内容。
  • 任何其他更改我的代码

标签: java android database sqlite import


【解决方案1】:

没有你的 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();
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 2018-01-27
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 2012-01-05
      • 2018-12-26
      相关资源
      最近更新 更多