0

我遇到了一个奇怪的情况。我在我的大多数项目中都使用了这个代码并且工作正常,但是我在一个新项目中使用它并且它不起作用我的意思是我的数据库没有复制到用户的手机中。我查看了每一行并向每种方法添加了日志,但我没有收到任何日志。应用程序工作正常,除了数据库部分。

数据库适配器:

public class DBAdapter extends SQLiteOpenHelper {

private static String DB_PATH;
private static String DB_NAME = "dictionary.db";
SQLiteDatabase db;
private Context c;



DBAdapter(Context context) {
    super(context, DB_NAME, null, 1);
    c = context;
    try {
        createDataBase();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public void createDataBase() throws IOException {
    boolean dbExist = checkDataBase();
    if (dbExist) {
        Toast.makeText(c,"done",Toast.LENGTH_LONG).show();
    } else {
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            throw new Error("Can't copy database" + e);
        }
    }

}

private boolean checkDataBase() {
    DB_PATH = c.getApplicationInfo().dataDir + "/databases/";
    File dbFile = new File(DB_PATH + DB_NAME);
    return dbFile.exists();
}

private void copyDataBase() throws IOException {
    DB_PATH = c.getApplicationInfo().dataDir + "/databases/";
    InputStream inputStream = c.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    OutputStream outputStream = new FileOutputStream(outFileName);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer))>0) {
        outputStream.write(buffer,0, length);
    }
    outputStream.flush();
    outputStream.close();
    inputStream.close();
}

public void openDataBase() {
    DB_PATH = c.getApplicationInfo().dataDir + "/databases/";
    String myPath = DB_PATH + DB_NAME;
    db = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.NO_LOCALIZED_COLLATORS);

}

@Override
public synchronized void close() {
    if (db != null)
        db.close();
    super.close();
}
}
4

0 回答 0