FileObserver & # 8594; onEvent (event, path): NULL path

I want to know when the file is finished, and for this I am trying to use FileObserver . I do it like this:

 FileObserver observer = new FileObserver(imageUri.getPath()) { @Override public void onEvent(int event, String path) { if(event == FileObserver.CLOSE_WRITE) Log.d(TAG, "FILE: "+path); } }; observer.startWatching(); 

imageUri is a valid Uri . When the file is closed, I get the following log entry:

 FILE: null 

Why is this null ? Perhaps the user writes several files, so I need to know which one fires the event.

Thanks!

+4
source share
2 answers

According to the onEvent() documentation :

Path relative to the main monitored file or directory of the file or directory that caused the event

So, I think when path is null , is the specified file or directory ...

You need to track the source path yourself. And add path of onEvent() to this path to get the full path (if you don't track the file, and its value is always null ):

 FileObserver observer = new FileObserver(imageUri.getPath()) { public String basePath; @Override public void onEvent(int event, String path) { String fullPath = basePath; if(path != null) { // Eventually add a '/' in between (depending on basePath) fullPath += path; } Log.d(TAG, "FILE: "+fullPath); } }; observer.basePath = imageUri.getPath(); observer.startWatching(); 

I tried to bring this example as close as possible to a piece of code. But it is much better to create a full-blown class that extends FileObserver , so you can add a constructor to store basePath and you don’t have to access a public field outside the class / instance!

+6
source

I just met something similar today. I had FileObserver tracking the folder for new files, and then I tried to do something with the uploaded images. When I went to access images using BitmapFactory.decodeFile (ImgPath), sometimes I get a NULL result. It seemed to happen on newer and faster devices and never debugged when going through an event. I came to the conclusion that the file is still in use or not yet fully completed, and I had to wait until the system released its claws from the file.

I'm new to Android development and don't know a suitable way to do this, but avoided the NULL problem for now by inserting Thread.sleep. I know this is terrible, but for me it worked as a temporary solution.

+3
source

All Articles