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 に答える