正在尝试将我的sqlite数据库导入Android

正在尝试将我的sqlite数据库导入Android,android,sqlite,import,Android,Sqlite,Import,在本教程之后,我一直在尝试复制它,并且在Outputstream声明行中不断出现错误 我的代码如下: private void copyDataBase() throws IOException{ System.out.println("copyDatabase Start"); //Open your local db as the i

在本教程之后,我一直在尝试复制它,并且在Outputstream声明行中不断出现错误

我的代码如下:

private void copyDataBase() throws IOException{
                                                                            System.out.println("copyDatabase Start");
    //Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);
                                                                            System.out.println("copyDatabase: InputStream Set");
    // Path to the just created empty db
    String outFileName = "/data/data/com.example.sqllitedb_user/databases/";
                                                                            System.out.println("copyDatabase: outFileName:" + outFileName);
    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);
                                                                            System.out.println("copyDatabase: FileOutputStream set to above name");
    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }
                                                                            System.out.println("copyDatabase: byte buffer thing ran" );
    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
    System.out.println("copy Database complete");
}
我看到其他人也有同样的问题,我想知道解决办法是什么

是否有其他(更简单的)方法导入和访问我自己的sqlite表


忽略此帖子-结果是我忘记调用主要活动的初始化方法。

您可以尝试以下方法:

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 **/
private void copyDataBase() throws IOException {
    // Open your local db as the input stream
    final InputStream myInput = new FileInputStream(context.getCacheDir().getPath() + "/" + DB_NAME);
        //context.getAssets().open(DB_NAME);

    // Path to the just created empty db
    final String outFileName = dbPath + DB_NAME;

    // Open the empty db as the output stream
    final OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

我已经试过了,但是我怎样才能知道数据库是否正确并且传输是否正确呢?我在尝试查询时遇到了一个nullpointer异常(请参见此问题:),谢谢您的帮助。似乎我忘了调用主活动的初始化方法。很抱歉给您添麻烦。;-)