Search code examples
javaandroidfileobserver

Android FileObserver onEvent not getting called


Can someone possibly help me with this?

I want to observe a file to see if it gets modified so that I can update the activity. After several tests, I've determined it's just plain not working. Am I doing something wrong?

I'm creating a FileObserver with an onEvent method to display a Toast and log data just to see if it's working, however the onEvent is never getting called. I have tried it both with an existing and a new file, but it doesn't seem to work in either case.

    Context context = this;
    File fileFolder = context.getFilesDir();

    String fileName = "quest";
    FileObserver questObserver = new FileObserver(fileFolder.getPath()) { // also tried fileFolder.getName()
        @Override
        public void onEvent(int event, String path) {
            Toast.makeText(getApplicationContext(), "onEvent fired", Toast.LENGTH_LONG).show();
            Log.d(TAG, "FileObserver().onEvent");
        }
    };
    questObserver.startWatching();

    /* create file */
    ObjectOutputStream objectOut = null;
    try {
        FileOutputStream fileOut = context.openFileOutput(fileName, Context.MODE_PRIVATE);
        objectOut = new ObjectOutputStream(fileOut);
        objectOut.writeObject(new Quest());
        fileOut.getFD().sync();
    } catch (IOException e) {
        Log.d(TAG, e.getMessage());
    } finally {
        if (objectOut != null) {
            try {
                objectOut.close();
            } catch (IOException e) {
                Log.d(TAG, e.getMessage());
            }
        }
    }

    /* read file */
    ObjectInputStream objectIn = null;
    Quest quest = null;

     try {
         FileInputStream fileIn = context.openFileInput(fileName);
         objectIn = new ObjectInputStream(fileIn);
         quest = (Quest) objectIn.readObject();
     } catch (FileNotFoundException e) {
         // Do nothing
     } catch (IOException e) {
         e.printStackTrace();
     } catch (ClassNotFoundException e) {
         e.printStackTrace();
     } finally {
         if (objectIn != null) {
             try {
                 objectIn.close();
             } catch (IOException e) {
                 Log.d(TAG, e.getMessage());
             }
         }
     }
     Toast.makeText(context, quest.getTitle(), Toast.LENGTH_LONG).show();

    questObserver.stopWatching();

Any help would be greatly appreciated.


Solution

  • Assuming your file doesn't (always) exist you should probably put your observer on the files folder, obtained like so:

    Context ctx = ...;
    File filesFolder = ctx.getFilesDir();
    

    Note that this will also ensure that the filesFolder directory will be created.

    Your observer will now be notified whenever a file is written, deleted or updated using for instance Context#.openFileOutput(..) - and you can filter in your FileObserver for the file name, in your example "quest".