While trying to save an image I am getting the error message 'Unresolved reference:runOnUiThread' and also on the context terms inside the toast messages. The relevant code snippets are as below. I have tried all possible fixes, but failed. Please help!
private suspend fun saveDrawnView(myBitmap: Bitmap): String {
var result = ""
withContext(Dispatchers.IO) {
if (myBitmap != null) {
try {
val bytes = ByteArrayOutputStream()
myBitmap.compress(Bitmap.CompressFormat.PNG, 90, bytes)
// val externalCacheDir = null
val f = File(
getExternalStorageDirectory()?.absolutePath.toString() +
File.separator + "com.example.drawingboardforkids" + System.currentTimeMillis() / 1000 + ".PNG"
)
val fo = FileOutputStream(f)
fo.write(bytes.toByteArray())
fo.close()
result = f.absolutePath
runOnUiThread{
if (!result.isEmpty()) {
Toast.makeText(
this@MainActivity,
"File saved successfully :$result",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
this@MainActivity,
"Something went wrong while saving the file.",
Toast.LENGTH_SHORT
).show()
}
}
} catch (e: Exception) {
result = ""
e.printStackTrace()
}
}
}
return result
}
}
I've checked the coroutine dependencies inside build gradle, went throught clean, rebuild, invalidate caches, restart the pc etc., but the problem persists and hence the query. Please help!
The problem resolved. It occurred because the function was out of the scope of the MainActivity. Such a silly mistake..sorry for taking up the space and time.