I have a mobile app (done using MIT App Inventor) storing some values to a Firebase database. App inventor stores all the values as strings (i.e. with quotes, and strings have quotes enclosed within quotes eg. "\"hello\""
).
I'm using this library to fetch data from Firebase to ESP8266. I'm using String
var to store the value retrieved and then change it to a CString (trying to store it directly doesn't work) as below:
This doesn't work:
Firebase.get(firebaseData, "/SCHEDULE DETAILS/SCHEDULE1/FREQ FR");
Serial.print("node -- schedule1 /FREQ FR -- type: ");
Serial.println(firebaseData.dataType());
char * cstr1 = new char [33];
cstr1 = firebaseData.stringData();
Serial.print(" -- data: ");
Serial.println(cstr1);
This works:
Firebase.get(firebaseData, "/SCHEDULE DETAILS/SCHEDULE1/WEIGHT");
Serial.print("node -- schedule1/WEIGHT -- type: ");
Serial.println(firebaseData.dataType() ) ;
String dummy = firebaseData.stringData();
Serial.print(" -- data: ");
Serial.print(dummy);
char * cstr = new char [dummy.length()+1];
strcpy (cstr, dummy.c_str());
Serial.print(" -- data int type: ");
Serial.println(atoi(cstr)) ;
I have some more nodes to get data from and I've read that lots of Strings
are a bad practice. While trying to find out more, I saw the source code and stringData
function itself returns a CString:
I feel like I'm doing one step more than what is required! Any suggestions on how to go about this would be very useful!
Try1 Based on the answer from @Majenko, I tried this before adding to the library:
const char* get_cstring() {
String str = "will it work" ;
return str.c_str();
}
void setup() {
Serial.begin(9600);
}
void loop() {
const char *new_c = get_cstring();
int len = strlen(new_c);
for (int i = 0; i < len; i++) {
Serial.println(new_c[i]);
delay(1000);
}
Serial.println("----------");
}
But how do I access the contents, because it just prints garbage values; strlen(new_c)
gives 2 (I'm guessing that's the amount of storage needed in bytes!?)
Thanks!