javaandroidfileobserver

Trouble with startActivity() in file observers onEvent()


I've got a fileObserver running and now I need to start an activity after the onEvent gets called and I'm not quite sure how to do it considering I can't get startActivity().

Here's my current code:

public class snapObserver extends FileObserver {

public final String TAG = "DEBUG";
public static Context mContext;

public snapObserver(String path) {
    super(path, FileObserver.CREATE);
}

@Override
public void onEvent(int event, String path) {
    if (path == null){
        Log.d(TAG, "path is null");
    }

    Log.d(TAG, "File created!!!!");
    mContext.startActivity(new Intent(mContext, editActivity.class));
}
}

This code throws a java.lang.NullPointerException

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference at android.content.ComponentName.(ComponentName.java:77) at android.content.Intent.(Intent.java:3996) at com.samplersnapshoot.domiq.samplersnapshoot.snapObserver.onEvent(snapObserver.java:28) at android.os.FileObserver$ObserverThread.onEvent(FileObserver.java:122) at android.os.FileObserver$ObserverThread.observe(Native Method) at android.os.FileObserver$ObserverThread.run(FileObserver.java:85)

I have a service running in the background that calls the fileObserver with a simple startWatching.


Solution

  • Try doing this:

    public class snapObserver extends FileObserer {
        private Context mContext;
    
        //any code
    
        public snapObserver(String path, Context context) {
            super(path, FileObserver.CREATE);
    
            this.mContext = context;
        }
    
        //any code
    }