However, the database can't be used directly, it must be copied to the storage first.
In this sample code, the asset is copied to the internal storage if it isn't copied yet.
Context Context = getApplicationContext(); String DestinationFile = Context.getFilesDir().getPath() + File.separator + "DB.sqlite"; if (!new File(DestinationFile).exists()) { try { CopyFromAssetsToStorage(Context, "Database/DB.sqlite", DestinationFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void CopyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException { InputStream IS = Context.getAssets().open(SourceFile); OutputStream OS = new FileOutputStream(DestinationFile); CopyStream(IS, OS); OS.flush(); OS.close(); IS.close(); } private void CopyStream(InputStream Input, OutputStream Output) throws IOException { byte[] buffer = new byte[5120]; int length = Input.read(buffer); while (length > 0) { Output.write(buffer, 0, length); length = Input.read(buffer); } }The code assumes that the file to be copied is named 'DB.sqlite' and it resides in a folder named 'database' in the assets.
Thanks. Very helpful post.
ReplyDeleteI had to change the database DestinationFile as follows:
DestinationFile = Context.getDatabasePath("DB.sqlite").getPath();
The Content Provider could not find the database.
Thanks, i have been finding solution from last 5 days husshh
ReplyDeleteThanks, it was very helpful!
ReplyDelete