How to open file save dialog in android?
Asked Answered
D

5

9

I have a web service which give me a byte[] array according to image id . I want to convert these byte[] to file and store a file on android where user want like save file dialog box with file same format exactly it has.

Dandiprat answered 21/12, 2011 at 8:8 Comment(0)
U
3

You cant create a save file dialog but you can save files from ur application to android sd card with the help of below links

http://android-er.blogspot.com/2010/07/save-file-to-sd-card.html

http://www.blackmoonit.com/android/filebrowser/intents#intent.pick_file.new

Uzbek answered 21/12, 2011 at 8:54 Comment(2)
please provide a usable link in which user able to select location where he want to store file.Dandiprat
Create a edit text in ur app or create a dialog box with edit text.Write in edit text ur path where u want to save the file.get the path by using getText() and put the object in File file = new File(extStorageDirectory, "er.PNG"); at the place of er.PNG.Than final piece of code will be File file = new File(extStorageDirectory, "OBJECT");Uzbek
S
20

Since this is the top result in google when you search for that topic and it confused me a lot when I researched it, I thought I add an update to this question. Since Android 19 there IS a built in save dialog. You dont event need any permission to do it (not even WRITE_EXTERNAL_STORAGE). The way it works is pretty simple:

//send an ACTION_CREATE_DOCUMENT intent to the system. It will open a dialog where the user can choose a location and a filename

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("YOUR FILETYPE"); //not needed, but maybe usefull
intent.putExtra(Intent.EXTRA_TITLE, "YOUR FILENAME"); //not needed, but maybe usefull
startActivityForResult(intent, SOME_INTEGER);

...

//after the user has selected a location you get an uri where you can write your data to:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if(requestCode == SOME_INTEGER && resultCode == Activity.RESULT_OK) {
    Uri uri = data.getData();

    //just as an example, I am writing a String to the Uri I received from the user:

    try {
      OutputStream output = getContext().getContentResolver().openOutputStream(uri);

      output.write(SOME_CONTENT.getBytes());
      output.flush();
      output.close();
    }
    catch(IOException e) {
      Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
    }
  }
}

More here: https://developer.android.com/guide/topics/providers/document-provider

Sienna answered 28/10, 2018 at 11:38 Comment(3)
I was under the impression that OutputStream.close() automatically does a flush(). But apparently it doesnt. Thanks ill edit it :DSienna
intent.setType("/") was required by me. Otherwise I got "No activity found to handle Intent - android.intent.action.OPEN_DOCUMENT"Johnson
intent.setType("/") ;Erleneerlewine
N
4

The Android SDK does not provide its own file dialog, therefore you have to build your own.

Nisan answered 21/12, 2011 at 8:11 Comment(0)
K
4

First, you should create a dialog intent for saving the file, After selection by the user, you can write on that directory and specified the file without any read/write permissions. ( Since Android 19 )

Source:https://developer.android.com/training/data-storage/shared/documents-files#create-file

   // Request code for creating a PDF document.
    private final int SAVE_DOCUMENT_REQUEST_CODE = 0x445;
    private File targetFile;
 
   private void createFile() {
            Uri reportFileUri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", targetFile);
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/pdf");
        intent.putExtra(Intent.EXTRA_TITLE, targetFile.getName());
    
        // Optionally, specify a URI for the directory that should be opened in
        // the system file picker when your app creates the document.
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
        startActivityForResult(intent, SAVE_DOCUMENT_REQUEST_CODE );
    }

   
        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable 
            Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == SAVE_DOCUMENT_REQUEST_CODE && resultCode == RESULT_OK){
                Uri uri = data.getData();
                saveFile(uri);
            }
        }
     
         private void saveFile(Uri uri) {
                try {
                    OutputStream output = getContentResolver().openOutputStream(uri);
                    FileInputStream fileInputStream = new FileInputStream(targetFile);
                    byte[] bytes = new byte[(int) targetFile.length()];
                    fileInputStream.read(bytes, 0, bytes.length);
                    output.write(bytes);
                    output.flush();
                    output.close();
                    Log.i(TAG, "done");
                } catch (IOException e) {
                    Log.e(TAG, "onActivityResult: ", e);
                }
            }
Kawai answered 14/2, 2021 at 9:13 Comment(0)
U
3

You cant create a save file dialog but you can save files from ur application to android sd card with the help of below links

http://android-er.blogspot.com/2010/07/save-file-to-sd-card.html

http://www.blackmoonit.com/android/filebrowser/intents#intent.pick_file.new

Uzbek answered 21/12, 2011 at 8:54 Comment(2)
please provide a usable link in which user able to select location where he want to store file.Dandiprat
Create a edit text in ur app or create a dialog box with edit text.Write in edit text ur path where u want to save the file.get the path by using getText() and put the object in File file = new File(extStorageDirectory, "er.PNG"); at the place of er.PNG.Than final piece of code will be File file = new File(extStorageDirectory, "OBJECT");Uzbek
M
0

@JodliDev already provided the accepted answer, however, startActivityForResult is now deprecated, so I want to provide my solution here using registerForActivityResult(ActivityResultContracts.CreateDocument())

First register a ActivityResultLauncher where you define what should happen with the result. We'll get the uri back that we can use for our OutpuStream. But make sure to initialize it at the beginning, otherwise you will get:

Fragments must call registerForActivityResult() before they are created (i.e. initialization, onAttach(), or onCreate()).

private var ics: String? = null
private val getFileUriForSavingICS = registerForActivityResult(ActivityResultContracts.CreateDocument()) { uri ->
    if(ics.isNullOrEmpty())
        return@registerForActivityResult
    try {
        val output: OutputStream? =
            context?.contentResolver?.openOutputStream(uri)
        output?.write(ics?.toByteArray())
        output?.flush()
        output?.close()
    } catch (e: IOException) {
        Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show()
    }
}

Then just call your ActivityResultLauncher with .launch(...) wherever it is needed.

getFileUriForSavingICS.launch("filename.txt")

And that's about it ;-) You can also have a closer look at ActivityResultContracts.CreateDocument(). This method provides the document saving dialog, but there are other helpful functions inside (like for starting a camera intent). Check out: https://developer.android.com/reference/androidx/activity/result/contract/ActivityResultContracts for the possible ActivityResultContracts

Or https://developer.android.com/training/basics/intents/result for some more training material and also some information how a custom contract could be created!

Mclean answered 24/1, 2022 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.