1

My android app create an csv file and share it immediately as the below code. The app start properly but there is no file attached when i select anyone of the application to share it. please kindly help to solve this issue.

class MainActivity : AppCompatActivity() {

    private val CSV_HEADER = "id,name,address,age"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        val qponFile = File.createTempFile("qpon", "csv")
        var fileWriter: FileWriter? = null

        try {
            fileWriter = FileWriter("qpon.csv")

            fileWriter.append(CSV_HEADER)
            fileWriter.append('\n')


                fileWriter.append("aaaaa")
                fileWriter.append(',')
                fileWriter.append("bbbbb")
                fileWriter.append(',')
                fileWriter.append("cccccc")
                fileWriter.append(',')
                fileWriter.append("dddddd")
                fileWriter.append('\n')

            println("Write CSV successfully!")

        } catch (e: Exception) {
            println("Writing CSV error!")
            e.printStackTrace()
        }


        val sendIntent = Intent()
        sendIntent.action = Intent.ACTION_SEND
        sendIntent.putExtra(Intent.EXTRA_STREAM, qponFile)
        sendIntent.type = "text/csv"
        startActivity(Intent.createChooser(sendIntent, "SHARE"))

    }

}

Image1,the app start properly. enter image description here

Image2, no attachment enter image description here

GPH
  • 1,111
  • 6
  • 29
  • 49

2 Answers2

1

After writing to the file you must close it:
fileWriter.close()
and make this change:
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(qponFile))

0
val HEADER = "Name, DateTime"

var filename = "export.csv"

var path = getExternalFilesDir(null)   //get file directory for this package
//(Android/data/.../files | ... is your app package)

//create fileOut object
var fileOut = File(path, filename)

//delete any file object with path and filename that already exists
fileOut.delete()

//create a new file
fileOut.createNewFile()

//append the header and a newline
fileOut.appendText(HEADER)
fileOut.appendText("\n")
// trying to append some data into csv file
fileOut.appendText("Haider, 12/01/2021")
fileOut.appendText("\n")


val sendIntent = Intent(Intent.ACTION_SEND)
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fileOut))
sendIntent.type = "text/csv"
startActivity(Intent.createChooser(sendIntent, "SHARE"))
gawi
  • 2,843
  • 4
  • 29
  • 44
SA Faraz
  • 1
  • 1