Development Guide

Local Navigation

Copying a database to an encrypted location

If you copy a SQLite database to an encrypted storage location on a BlackBerry® smartphone (eMMC or microSD card), the database can become inaccessible to the Database API. This happens because the media card uses a different type of encryption from that used by the Database API.

To copy a database so that you can access it, you should use the Database API to create an empty database file, truncate the file to zero, and then copy the database into the file.

The following code sample demonstrates this technique.

// Copy a database to an encrypted storage location. 
 
private void copyDBRecommendedWay() {
          
    try { 
        String dbPath = "file:///SDCard/original.db";
        String dbPathCopy = "file:///SDCard/copy.db";             
        Database dbCopy = null;
        try {
            // Delete if there's an existing one.
            DatabaseFactory.delete(URI.create(dbPathCopy));
              
           // Create the database using the DatabaseFactory class.                
            dbCopy = DatabaseFactory.create(URI.create(dbPathCopy));
        } catch (DatabaseException e) {
           System.out.println( "DatabaseException: error code: " 
                  + e.getErrorCode() + " msg: " + e.getMessage());        
        } finally {
            // Close the database.
            dbCopy.close();            
        }
          
        // Open a connection to the database file that was created.
        FileConnection outfc = (FileConnection)Connector.open(dbPathCopy);
           
        // Truncate the file.
        outfc.truncate(0);
                       
        // Write out the downloaded database data to FileConnection.openOutputStream().
        OutputStream os = outfc.openOutputStream();
           
        FileConnection infc = (FileConnection)Connector.open(dbPath);        
        InputStream is = infc.openInputStream();
                       
        byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf)) > 0){
            os.write(buf, 0, len);
        }
        is.close();
        os.close();                     
           
        // Close the file connection.
        outfc.close();
           
        System.out.println("Copied " + dbPath + " to " + dbPathCopy);
           
        // The database can now be reopened with the DatabaseFactory class.
    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    }
}    

Was this information helpful? Send us your comments.