There is very nice library that I am using thanks to programmer which has made exporting very easy, but my concern is since Android 10, the file cannot be exported on internal memory of the device. The file gets exported under the package name. Well no issues there though, what I am trying is, I wan to use Intent.ACTION_CREATE_DOCUMENT, and let the user choose where to save the excel file that is generated from Sqlite Database.
Below is the code to convert sqlite to excel, it converts and automatically saves it to internal memory on Android < 10.
public void exportDBtoExcel() {
String folder;
Context context = getApplicationContext();
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Musajjal Report/";
File externalFolder = context.getExternalFilesDir(null);
folder = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Musajjal Report/" ;
File file = new File(folder); // this below 2 lines of code is for Android > 10
if (externalFolder != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
folder = externalFolder.getAbsolutePath();
}
boolean fileCreated = file.exists();
if ( !fileCreated ) {
fileCreated = file.mkdirs();
}
if ( fileCreated ) {
// Export SQLite DB as EXCEL FILE
SQLiteToExcel sqliteToExcel = new SQLiteToExcel(getApplicationContext(), StudentDatabase.DBname,folder);
sqliteToExcel.exportAllTables("Student.xls", new SQLiteToExcel.ExportListener() {
@Override
public void onStart() {
}
@Override
public void onCompleted(String filePath) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Report Generated");
builder.setMessage(filePath);
builder.setCancelable(false);
builder.setPositiveButton("Ok", (dialogInterface, i) -> builder.setCancelable(true));
builder.show();
}
@Override
public void onError(Exception e) {
Toast.makeText(getApplicationContext(), "Export Failed: " + e, Toast.LENGTH_LONG).show();
}
});
}
}
My question is how can I save the excel file using the File Manager , please help, Thank you in advance. I have tried using the below code but it does not seem to work, because the above method is converting and saving before I can use the File Manager to pick a location to save.
private void createFile() {
// when you create document, you need to add Intent.ACTION_CREATE_DOCUMENT
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
// filter to only show openable items.
intent.addCategory(Intent.CATEGORY_OPENABLE);
// Create a file with the requested Mime type
intent.setType("text/csv");
startActivityForResult(intent, WRITE_REQ);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == WRITE_REQ){
switch (resultCode){
case Activity
.RESULT_OK:
if (data != null && data.getData() != null){
exportDBtoExcel();
}
break;
case Activity.RESULT_CANCELED:
break;
}
}
}