2012-05-23 55 views
1

我是android开发新手。现在即时尝试使用sqlite数据库。我使用sqlite管理器创建了一个数据库sqlite文件。 我曾尝试下面的代码,它工作在模拟器罚款,但如果我在装置了发布应用程序崩溃,即,它显示一条警告消息CheckMobileForDatabase意外停止的应用程序,我的SDK版本是2.2(8)Android中导入数据库的问题

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(); 
    } 
    }  
    } 
+1

请张贴logcat的表现错误。 – Barak

+0

上面的代码在模拟器中工作正常,但我释放该项目它在模拟器中正常工作,应用程序崩溃,它显示一条警报消息应用程序CheckMobileForDatabase已意外停止。解决此问题 – NAZIK

+0

因此,使用插入的手机运行它,然后抓住logcat,当它崩溃并发布。没有看到*为什么*它失败了,我们什么也做不了,因为您发布的代码中没有任何明显的内容。 – Barak

回答

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(); 
} 
+0

谢谢,我会尝试您的代码 – NAZIK

1

它可能是由于以前存储在你的Android设备版本的数据库,请尝试删除从您的设备或代码数据库的变化版本,先前的DB使onupgrade将被称为

+0

我更改我的数据库版本但不工作 – NAZIK