When running the code below I get the error message:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.songapp/com.example.songapp.MainActivity}: java.io.FileNotFoundException:
/data/data/com.example.songapp/databases/songs.db: open failed: ENOENT (No such file or directory)
The code that gives error is this:
@Throws(IOException::class)
fun copyDataBase(context: Context, OUTPUT_DB_PATH: String, DB_NAME: String) {
print("*** in copyDataBase ***")
// Path to output database path (application database path).
var APP_DB_FILE_PATH = OUTPUT_DB_PATH + "/" + DB_NAME
// Path to input database file.
var INPUT_DB_PATH = "database/" + DB_NAME
// Open your local db as the input stream
// This is how to get path from assets directory
val databaseInput: InputStream = context.assets.open(INPUT_DB_PATH)
// Open the empty db as the output stream
val databaseOutput: OutputStream = FileOutputStream(APP_DB_FILE_PATH)
// Transfer bytes from the inputfile to the outputfile
val buffer = ByteArray(1024)
var length: Int
while (databaseInput.read(buffer).also { length = it } > 0) {
databaseOutput.write(buffer, 0, length)
}
// Close the streams
databaseOutput.flush()
databaseOutput.close()
databaseInput.close()
}
This is being called in the main activity as follows:
var DB_PATH = "/data/data/com.example.songapp/databases/"
var DB_NAME = "songs.db"
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Get context and supply it to the function
// This is where error happens, by disabling this the app run successful.
copyDataBase(this, DB_PATH, DB_NAME)
setContent {
Column() {
TopAppBar(title = { Text(text = "Nyimbo") })
ScrollableColumn(Modifier.fillMaxWidth()
.padding(10.dp)) {
lyricsPageComposable(lyricsMap = songMap)
}
}
}
}
}
I have a pre-populated SQLite database in the assets directory assets/database/songs.db and I expect it to be copied into /data/data/com.example.songapp/databases/songs.db. I do not know how to check whether copying has succeeded. What am I missing here? I know that the database file could not be found. Is that the path is not right? Could it be that the database was not copied? How could I tell? I'm using a physical Android phone for testing the app.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />and<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />