0

I'm running into a problem using a FileObserver to update a meta-database when new sqlites are added to a specific directory on the SD card. If I manually adb push a new sqlite to the directory, then call onEvent(FileObserver.CREATE, <filename>), it works perfectly. However, when I call FileObserver.startWatching() and adb push a new sqlite for the observer to catch on its own, it calls onEvent (with the same params as when I call it manually - I checked), opens the sqlite file fine, but fails to find any of its tables when I query the newly opened sqlite and throws a sqlite exception.

I'm using SQLiteDatabase's openDatabase() method, so it's not failing to find the original and creating an empty one (a common problem). Additionally, the same sqlite query made in the adb shell accesses the newly added sqlite's tables just fine.

Does anybody have any ideas why this might happen? My code seems to work fine based on the success of the manual call, so I'm looking for any quirks with FileObservers or SQLite on Android that I might have missed, as I'm new to both.

UPDATE: Further debugging shows that if I adb push a file and call onEvent(FileObserver.CREATE, <filename>) manually, then start the FileObserver watching and adb push the same file to the same location, the FileObserver executes those onEvent queries with no trouble locating the tables... not sure what this means.

user2048643
  • 283
  • 1
  • 3
  • 14

1 Answers1

0

I figured out the problem - Android's FileObserver's onEvent method, for a file creation event, executes immediately after the creation of the file, not waiting for the file to finish being written. I was running into a race condition where the onEvent method was attempting to query the database before the file had actually finished being written. When I adb pushed and then called onEvent manually, there was enough time for the file to be written, which is why it worked then.

The quick fix was for me to call the queries in onEvent for the parameter FileObserver.CLOSE_WRITE instead of CREATE. Since I'm working with read-only access to these databases, the only time they will be written is the first time, and the CLOSE_WRITE event won't be triggered until they are done and ready to be queried.

user2048643
  • 283
  • 1
  • 3
  • 14