I'm quite new to Kotlin and Android programming.
I tried to find solution for my problem everywhere and couldn't do it. but it seems so trivial.
How do I read a file formatted as .csv from the external storage to a map variable?
I would love the whole code in order to do it (for premission, reading etc), lets name the file myFile.csv and locate it on Download folder (or any othe folder if it is a problem)
I'm using android 11 (need to stay compatible in the future)
EDIT: I tried all the method listed in the answers that were in the other question that was connected to my question. I still always get: open failed: EACCES (Permission denied)
My First Try for MainActivity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setupPermissions()
val path = getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/LET/test.txt")
val resolver = applicationContext.contentResolver
val readOnlyMode = "r"
val parcelFile = resolver.openFileDescriptor(path.toUri(), readOnlyMode)
val fileReader = FileReader(parcelFile!!.fileDescriptor)
val reader = BufferedReader(fileReader)
var line: String?
while (reader.readLine().also { line = it } != null) {
Toast.makeText(this, line, Toast.LENGTH_LONG).show()
}
reader.close()
reader.close()
fileReader.close()
}
private fun setupPermissions() {
val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
if (permission == PackageManager.PERMISSION_GRANTED) {
val path = getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
101
)
}
}
}
My Second Try for MainActivity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setupPermissions()
val path = getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
Toast.makeText(this, path.toString(), Toast.LENGTH_LONG).show()
val letDirectory = File(path, "LET")
letDirectory.mkdirs()
val file = File(letDirectory, "test.txt")
val inputAsString = FileInputStream(file).bufferedReader().use { it.readText() }
}
private fun setupPermissions() {
val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
if (permission == PackageManager.PERMISSION_GRANTED) {
val path = getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
101
)
}
}
Thanks, Tal.