-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFirebaseDBCollectionToExcel.java
97 lines (80 loc) · 2.74 KB
/
FirebaseDBCollectionToExcel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
public class FirebaseDBCollectionToExcel {
private String excelData;
private String[] fieldsNames;
private File file;
public FirebaseDBCollectionToExcel(String[] fieldsNames) {
//Initialize properties
this.fieldsNames = fieldsNames;
excelData = "";
file = null;
//Initialize header in Excel file
for ( int i = 0; i < fieldsNames.length; i++) {
excelData += "\"" + fieldsNames[i] + "\"";
if ( i < fieldsNames.length - 1)
excelData += ",";
else
excelData += "\n";
}
}
public void buildFileFromQuery(QueryDocumentSnapshot document ) {
String rowData = "";
for ( int i = 0; i < fieldsNames.length; i++) {
rowData += "\"" + document.getString(fieldsNames[i]) + "\"";
if ( i < fieldsNames.length - 1)
rowData += ",";
else
rowData += "\n";
}
excelData += rowData;
}
public void saveFileToStorage(String fileName, String dirName) {
file = null;
File root = Environment.getExternalStorageDirectory();
if ( root.canWrite()) {
File dir = new File ( root.getAbsolutePath() + "/" + dirName);
dir.mkdirs();
file = new File( dir, fileName + ".csv");
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
out.write(excelData.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void shareFileToEmail( String subject) {
Uri u1 = null;
u1 = Uri.fromFile(file);
Intent sendIntent = new Intent( Intent.ACTION_SEND);
sendIntent.putExtra( Intent.EXTRA_SUBJECT, subject);
sendIntent.putExtra( Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);
}
}