Skip to content

Instantly share code, notes, and snippets.

@tsherdiwala
Created July 6, 2019 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsherdiwala/b5af5c4eddea51ca64c1a02c250511d2 to your computer and use it in GitHub Desktop.
Save tsherdiwala/b5af5c4eddea51ca64c1a02c250511d2 to your computer and use it in GitHub Desktop.
Android database exporter
import android.content.Context
import android.util.Log
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
private val TAG = DatabaseExporter::class.java.simpleName
object DatabaseExporter {
fun exportDatabase(context: Context, dbName: String) {
val suffixes = listOf("", "-shm", "-wal")
for (suffix in suffixes) {
val targetFile = File(context.getExternalFilesDir(null), "export.db$suffix")
val dbFile = context.getDatabasePath(dbName + suffix)
if (dbFile.exists()) {
val dest = FileOutputStream(targetFile).channel
val src = FileInputStream(dbFile).channel
dest.transferFrom(src, 0, src.size())
src.close()
dest.close()
Log.d(TAG, "Exported from ${dbFile.absolutePath} to : ${targetFile.absolutePath}")
} else {
Log.d(TAG, "Cannot export file")
}
}
}
}
@tsherdiwala
Copy link
Author

Export database to public directory so that it could debugged

@tsherdiwala
Copy link
Author

tsherdiwala commented Jul 7, 2019

Beginning with Android 4.4 (API level 19), reading or writing files in your app's private external storage directory—accessed using getExternalFilesDir()—does not require the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permissions. So if your app supports Android 4.3 (API level 18) and lower, you should declare that the permission be requested only on the lower versions of Android by adding the maxSdkVersion attribute:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
                     android:maxSdkVersion="18" />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment