Search code examples
androiddatabasearraylistdynamic-dataandroid-sensors

Android: How to save sensor data onSensorChanged to a database?


I'm writting an android app in which I'm acquiring the accelerometer data from the sensor of the phone until the user quits. Afterwards I modify the data and try to save it to an existent database. Everything works fine, but when I'm calling my saveToDatabase() method in the onSensorChanged method, then the app starts to work extremely slow and becomes unresponsive and crashes shortly after. So, the problem is that i'm calling saveToDatabase() too often...

Is there a way to avoid that?

  • May be with an ArrayList/LinkedList/ArrayDeque where the sensor data have to be collected and after 5mins saved to the DB?
  • Or put everything in a Buffer and when the user exits then extract everything from it to the database?
  • Modify the saveToDabase method so that it uses beginTransaction instead of the insert-method?

        protected void saveToDatabase(){
             contentValues.put("SensorSensitivity", sensorSensitivity);
             contentValues.put("AccDataX", accelerometerData[0]);
             contentValues.put("AccDataY", accelerometerData[1]);
             contentValues.put("AccDataZ", accelerometerData[2]);
             contentValues.put("timeStamp", System.currentTimeMillis());
             long affectedColumnId = sqliteDatabase.insert("tName", null, contentValues);
             contentValues.clear();
    }
    

Solution

  • Android documentation suggest on every place where you work with IO, use different thread for disk manipulation.

    I suggest you should use one thread to receive onSensorChanged events, save it to memory, maybe add timestamp and values. Add several such values to array, then use handler or other way to pass this structure to another thread. That thread should save it into database, ie. Loop through all gathered values and save each like your saveToDatabase. This way. UI should be responsive all time, even when long queue waits to be written to disk.

    This might work, but there should be some feedback about how fast saving of values is and how big is incoming queue. If it is too long, you might drop some values to prevent full memory. Maybe saving thread would send using handler event to UI thread, that queue is full and it does not want new values for a while. When it reduces queue or make it empty, it would tell UI thread to start sending again.