An issue regarding reading data from my sqlite and sending it as a csv file to storage database

I'm having a persistent issue with my flutter app.

I have only two functions where the issue is happening.

The first function inserts data and reads the last 10 recrods from my sqlite database.

Future<void> _insertSensorData(AccelerometerEvent event) async {

  if (_database == null) return;

  // date
  final timestamp = DateTime.now();

  final formattedTime = DateFormat('yyyy-MM-dd HH:mm:ss').format(timestamp);
  
  // database
  final values = await _database!.transaction((txn) async {
    // Insert sensor data

    await txn.insert('sensor_data', {
      'timestamp': formattedTime,
      'x': event.x,
      'y': event.y,
      'z': event.z,
    });

    // Query the latest 10 entries
    return await txn.query(
      'sensor_data',
      orderBy: 'id DESC',
      limit: 10,
    );
  });

  // If no data is returned, exit early
  if (values.isEmpty) return;

  print(values);

  // Convert data to CSV outside the transaction to avoid extended locks
  final csv = ListToCsvConverter().convert([
    ["ID", "Timestamp", "X", "Y", "Z"],
    ...values.map((row) => [
          row['id'],
          row['timestamp'],
          row['x'],
          row['y'],
          row['z'],
        ])
  ]);

  // Upload CSV data to Firebase
  await _uploadToFirebase(csv);
}

The second function is for putting the data in a CSV file and uploads it to firebase storage.

Future<void> _uploadToFirebase(String csv) async {
  try {

    // Authenticate
    if (FirebaseAuth.instance.currentUser == null) {

      await FirebaseAuth.instance.signInAnonymously();

    }

    // storage directory
    final directory = await getApplicationDocumentsDirectory();

    final file = File(
        '${directory.path}/sensor_${DateTime.now().millisecondsSinceEpoch}.csv');

    // Write file
    await file.writeAsString(csv);

    // Upload
    final bytes = await file.readAsBytes();

    final ref = FirebaseStorage.instance
        .ref()
        .child("sensor_data/${DateTime.now().millisecondsSinceEpoch}.csv");

    final snapshot = await ref.putData(
      bytes,
      SettableMetadata(contentType: 'text/csv'),
    );
    print("✅ Upload completed: ${await snapshot.ref.getDownloadURL()}");

  } catch (e) {
    if (e.toString().contains('INTERNAL_STATE_CANCELED')) return;
    print("❌ Upload error: ${e.toString()}");
  }
}

all the errors(or actually warnings) start once the code reaches this line:

final snapshot = await ref.putData(
  bytes,
  SettableMetadata(contentType: 'text/csv'),
);

Here are the errors:

W/StorageUtil(29039): Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: No AppCheckProvider installed.

W/StorageTask(29039): unable to change internal state to: INTERNAL_STATE_CANCELED, INTERNAL_STATE_CANCELING isUser: true from state:INTERNAL_STATE_SUCCESS

I/flutter (29039): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction

I have been trying many solutions from the stackoverflow:

For the first warning seems like it wonts affect the app.

For the second one i have changed the method from ref.putFile to ref.putData, updating all the dependencies and I added a condition to make sure that the data are being sent to the storage safely and indeed I'm getting the data in the storage.

For the last error I have tried to use transaction and batch, but none worked.

The data are being sent and the code doing what i want, but these errors are still there.

As a note: the sensor data are accelerometer data that I'm continuously reading and saving it to the sqlite and I had no issue while just reading it and printing it continously on the screen.

Upvotes: 0

Views: 29

Answers (0)

Related Questions