Search code examples
androidjsoncsvfirebase-realtime-databaseopencsv

Print Firebase dataset on CSV in Android


I'm developing an android application for scan nearby Bluetooth devices & get detail of those devices. details mean Device Name, Device Address, RSSI like that. Then I send those data to the firebase realtime database. below I have mentioned my database structure.

enter image description here

I want to retrieve specific dataset and load those data to table in csv file Here I have mentioned how I get the dataset

protected void onStart() {
    super.onStart();

    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("BluetoothDevicesInfo");

    reference.orderByChild("deviceId").equalTo("C6:89:AF:D6:7B:83").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot deviceInf: dataSnapshot.getChildren()){
                String deviceId= deviceInf.child("deviceId").getValue().toString();
                Map<String, String> value = (Map<String, String>) dataSnapshot.getValue();
                Log.i("dataSnapshot", "dataSnapshot : " + new JSONObject(value));
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

Output

{"-M8Bu8znHpC4EAstfPLf": 
{"rssi":-92,"distance":1,"deviceId":"C6:89:AF:D6:7B:83","timestamp":"25-05-202023:06:52"}, 
 "-M8Bu8zOuBZjgkkSUcnG": 
{"rssi":-92,"distance":1,"deviceId":"C6:89:AF:D6:7B:83","timestamp":"25-05-2020 23:06:52"}}

How can I print this on CSV


Solution

  • Add these two at their respective positions.

    Doc

    maven { url 'https://jitpack.io' }

    implementation 'com.github.hsmnzaydn:easy-csv:1.0.0'.

    Declare some global variable

    List<String> headerList = new ArrayList<>();
    List<String> dataList = new ArrayList<>();
    Snapobj snap ;
    List<Snapobj > snapList = new ArrayList<Snapobj>();
    public final int WRITE_PERMISSON_REQUEST_CODE =1;
    

    Inside onCreate

     EasyCsv easyCsv = new EasyCsv(MainActivity.this);
     easyCsv.setSeparatorColumn("^");
     easyCsv.setSeperatorLine("~");
     headerList.add("rssi^distance^deviceId^timestamp~");
    

    Create a Snapobj class

    public class Snapobj {
    String rssi;
    String distance;
    String deviceId;
    String timestamp;
    
    public Snapobj(String rssi, String distance, String deviceId, String timestamp) {
        this.rssi = rssi;
        this.distance = distance;
        this.deviceId = deviceId;
        this.timestamp = timestamp;
    }
      //Add Getters and Setters
    }
    

    Now inside onDataChange we will fill snapList

    public void onDataChange(DataSnapshot dataSnapshot) {
      for(DataSnapshot deviceInf: dataSnapshot.getChildren()){
          snapList.add(new Snapobj("pass rssi","pass distance","deviceId","timestamp"));
        }
    }
    

    Now we need to construct string for data list array.Create a function and put these lines

    for(Snapobj s : snapList)
    {
      String s = s.getRssi()+"^"+s.getDistance()+"^"+s.getDeviceId()+"^"+s.getTimestamp()+"~";
      dataList.add(s);
    }
    

    Finally create the csv file.

    easyCsv.createCsvFile("MyFile", headerList, dataList WRITE_PERMISSON_REQUEST_CODE, new 
    FileCallback() {
    @Override
    public void onSuccess(File file) {
    Log.d(TAG, "File saved in phone storage");
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(MainActivity.this,"com.example.mafiacsv.fileprovider",file));
    sendIntent.setType("text/*");
    sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Intent shareIntent = Intent.createChooser(sendIntent, null);
    startActivity(shareIntent);
    }
    
    @Override
    public void onFail(String err) {
    }
    });
    

    Put this inside your application tag in ManifestFile

        <provider
            android:name=".GenericFileProvider"
            android:authorities="com.example.mafiacsv.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    

    Create a empty class that just extends FileProvider.

      import androidx.core.content.FileProvider;
      public class GenericFileProvider extends FileProvider {}
    

    onSuccess is called when the file has been successfully created and saved in your phone's internal storage.

    Important

    Make sure value of rssi, distance, id & timestamp does not contain '^' and '~' else it wouldn't work properly. We need two unique symbols to tell the library when to break the line and when to seperate column.

    Don't forget to ask WRITE_EXTERNAL_STORAGE permission.