2013-08-31 31 views
0

按照教程here我一直在试图复制这个,并且我一直在Outputstream声明行上发生错误。尝试将我的sqlite数据库导入到Android

我下面的代码是在这里:

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表?

IGNORE THIS POST - 原来我忘了在我的主要活动中调用初始化方法。

回答

1

你可以尝试这样的事情:

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

我已经试过,但我怎么能找到,如果数据库是正确的,它正确地转移?当我试图查询它时,我一直在收到一个空指针异常(请参阅此问题:http://stackoverflow.com/questions/18564442/obtaining-cursor-from-sqlite-database) – AKTStudios

+0

感谢您的帮助。看来我忘了在主要活动中调用初始化方法。抱歉,添麻烦了。 ;-) – AKTStudios

+0

没问题。真高兴你做到了:) – Vladan

相关问题