T
T
Tsuzukeru2021-01-25 13:12:40
Android
Tsuzukeru, 2021-01-25 13:12:40

Why is the file not saved in External Storage?

I study data storage in Android according to the book Saving Data on Android by raywenderlich.
Their example uses the methods of such a repository.

class ExternalFileRepository(var context: Context) :
    NoteRepository {

  override fun addNote(note: Note) {
    if (isExternalStorageWritable()) {
      FileOutputStream(noteFile(note.fileName)).use { output ->
        output.write(note.noteText.toByteArray())
      }
    }
  }

  override fun getNote(fileName: String): Note {
    val note = Note(fileName, "")
    if (isExternalStorageReadable()) {
      FileInputStream(noteFile(fileName)).use { stream ->
        val text = stream.bufferedReader().use {
          it.readText()
        }
        note.noteText = text
      }
    }
    return note
  }

  override fun deleteNote(fileName: String): Boolean {
    return isExternalStorageWritable() && noteFile(fileName).delete()
  }

  private fun noteDirectory(): File? = context.getExternalFilesDir(null)

  private fun noteFile(fileName: String): File = File(noteDirectory(), fileName)

  fun isExternalStorageWritable(): Boolean {
    return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
  }

  fun isExternalStorageReadable(): Boolean {
    return Environment.getExternalStorageState() in
        setOf(Environment.MEDIA_MOUNTED, Environment.MEDIA_MOUNTED_READ_ONLY)
  }

}


Permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


The problem is that the file is not saved along the path sdcard/data/app_name , and indeed it is not saved anywhere.
smartphone - Meizu m8, Android 8.1 Oreo
What could be the problem?

The isExternalStorageWritable() method returns true, and the file writing code is executed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
illuzor, 2021-01-25
@iLLuzor

You need to request permission from the user
https://developer.android.com/guide/topics/permiss...
https://source.android.com/devices/tech/config/run...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question