Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
15
rated 0 times [  16] [ 1]  / answers: 1 / hits: 21861  / 7 Years ago, sun, august 13, 2017, 12:00:00

My React Native app (on android only) is a basic app that will collect some sensors data when users start recording video. I have three arrays of sensors data: accelerometer, gyroscope, and light. I want to save them to the device as .csv files so I can use them for the next steps. Currently, I can save them in .txt (using react-native-fs, but they do not support .csv extension) but what I want is .csv. Is there any way to do that in React Native?



Data will look like this:



this.accelerometer = [
{x: 12, y: 15, z: 17},
{x: 12, y: 15, z: 17},
...
{x: 12, y: 15, z: 17},
]

this.gyroscope = [
{x: 12, y: 15, z: 17},
{x: 12, y: 15, z: 17},
...
{x: 12, y: 15, z: 17},
]

this.light = [6, 7, 8, 9, 10,.., 11]


Desired .csv, for example accelerometer.csv:



x ,y ,z
12,15,17

More From » android

 Answers
14

You can use react-native-fetch-blob to write to the device's file system. (I was wondering this too!)



We start by converting an array of values to a string. If our values are separated by , commas and our rows are separated by n newlines, then our string is csv. We can take that string, write it to a file with a .csv file extension, and voila we have a .csv file.



here's code that does just this:



import RNFetchBlob from 'react-native-fetch-blob';

const values = [
['build', '2017-11-05T05:40:35.515Z'],
['deploy', '2017-11-05T05:42:04.810Z']
];

// construct csvString
const headerString = 'event,timestampn';
const rowString = values.map(d => `${d[0]},${d[1]}n`).join('');
const csvString = `${headerString}${rowString}`;

// write the current list of answers to a local csv file
const pathToWrite = `${RNFetchBlob.fs.dirs.DownloadDir}/data.csv`;
console.log('pathToWrite', pathToWrite);
// pathToWrite /storage/emulated/0/Download/data.csv
RNFetchBlob.fs
.writeFile(pathToWrite, csvString, 'utf8')
.then(() => {
console.log(`wrote file ${pathToWrite}`);
// wrote file /storage/emulated/0/Download/data.csv
})
.catch(error => console.error(error));


this approach worked for me on an Android 7.x test device.



in case it's helpful, I'll also share a link to the equivalent code inside my react-native project


[#56783] Thursday, August 10, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
julieth

Total Points: 382
Total Questions: 99
Total Answers: 85

Location: Cape Verde
Member since Fri, Nov 27, 2020
4 Years ago
;