'Using ACTION_CREATE_DOCUMENT to create a CSV file

I'm trying to create a file that will specifically be a .csv filetype using the ACTION_CREATE_DOCUMENT intent. Here is the code I currently have:

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TITLE, ".csv");
startActivityForResult(intent, myRequestCode);

And here is the code for my onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent dataIntent) {
    super.onActivityResult(requestCode, resultCode, dataIntent);

    // TODO: make the requestCode a global variable
    if (resultCode == RESULT_OK && dataIntent != null ) {
        if (requestCode == 0) { // user clicked "Database CSV"
            try {
                if(! dataIntent.getData().getPath().endsWith(".csv")) {
                    
                }

                OutputStream outputStream = getContentResolver().openOutputStream(dataIntent.getData());
                myDb.export_toDatabaseCSV_withOutputStream(outputStream);
                Toast.makeText(getApplicationContext(), "Successfully exported.", Toast.LENGTH_LONG).show(); // TODO: make this an actual check based on the result of myDb.export
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "File could not be created.", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }
    }
}

The Uri path returned from dataIntent.getData().getPath() = "/document/primary:Download/myFileName". I can't seem to find a way to edit the File's name inside of the the if statement.

EXTRA_TITLE has similar functionality to what I want, but isn't quite what I need. I want users to be able to specify the filename in the activity without having to add .csv to the end of the file name. For example, if a user creates a file named "MyData", when the activity ends I want the file to be renamed "MyData.csv".



Solution 1:[1]

Use this, it should work

   intent.setType("text/comma-separated-values")

If possible kindly share with us this function that you have used myDb.export_toDatabaseCSV_withOutputStream(outputStream);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 metvsk