I have this code:
private void requestPermissionAndExport() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
export();
} catch (IOException e) {
e.printStackTrace();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public void export() throws IOException {
String csv_data = "testtest";
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
root = new File(root, "my_csv.csv");
try {
FileOutputStream fout = new FileOutputStream(root);
fout.write(csv_data.getBytes());
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
It works when I first install and launch the app. If the user deletes the csv
file from the download folder and try to open the app again, and export csv
again, nothing happens. Also if I generate every time differents name for the file, only the first one (after installation of the app) is created.
Why does this work only in the first instance?
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
export();
} catch (IOException e) {
e.printStackTrace();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Probably that's why. You call export()
only inside onRequestPermissionsResult()
and app asks for permissions only once, and remember it till you uninstall it. Try it yourself: if you clear app data from app manager it will ask again, and then export file again too.