Search code examples
javaandroidscoped-storage

how to save file to external storage, currently it creates document but it size is 0B


I want to backup my database with new methods,my target sdk is 30, I don't know what i am doing wrong here. I am passing type to setType but it only creates file with 0B. how can i properly backup database.

What i am currently doing is

Intent i = new Intent(Intent.ACTION_CREATE_DOCUMENT);
i.setType("application/x-sqlite3");
i.putExtra(Intent.EXTRA_TITLE, DATABASE_NAME);
startActivity(i);
Toast.makeText(this, "done", Toast.LENGTH_SHORT).show();

so how can i store my database with data to external storage when user presses export button

enter image description here


Solution

  • first, start activity for result

    Intent i = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    i.setType("application/x-sqlite3");
    startActivityForResult(i, BACKUP_CODE);
    

    after this it will create file with size of 0 B so we have to write backup in onActivityResult.

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == BACKUP_CODE) {
            try {
                assert data != null;
                FileOutputStream stream = (FileOutputStream) getContentResolver().openOutputStream(data.getData());
                Files.copy(Paths.get(getDatabasePath(DATABASE).toPath()), stream);
                Toast.makeText(this, "done", Toast.LENGTH_SHORT).show();
                stream.close(); ///very important
            } catch (Exception e) {
                Toast.makeText(this, "Error occurred in backup", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }
    }
    

    it'll successfully creates backup. It worked for me.