Cordova unable to get file directory using .getFilesDir()

745 views Asked by At

I am trying to get the following code to work in my cordova plugin.

private void loadPatch() throws IOException {

    //File dir = this.cordova.getActivity().getApplicationContext().getFilesDir(); //this throws same error
    //File dir = cordova.getActivity().getFilesDir(); //throws same error
    File dir = cordova.getActivity().getApplicationContext().getFilesDir();

    IoUtils.extractZipResource(cordova.getActivity().getResources().openRawResource(R.raw.patch),
            dir, true);
    File patchFile = new File(dir, "microphone.pd");
    PdBase.openPatch(patchFile.getAbsolutePath());
    PdAudio.startAudio(this.cordova.getActivity());

}

However when I run the application, I get nullPointExceptionError on the line below

File dir = cordova.getActivity().getApplicationContext().getFilesDir();

Here is the stack

Thread [<1> main] (Suspended (exception NullPointerException))  
    <VM does not provide monitor information>   
    Libpd.loadPatch() line: 83  
    Libpd.access$2(Libpd) line: 79  
    Libpd$1.run() line: 54  
    Handler.handleCallback(Message) line: 733   
    Handler.dispatchMessage(Message) line: 95   
    Looper.loop() line: 136 
    ActivityThread.main(String[]) line: 5333    
    Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
    Method.invoke(Object, Object...) line: 515  
    ZygoteInit$MethodAndArgsCaller.run() line: 895  
    ZygoteInit.main(String[]) line: 711 
    NativeStart.main(String[]) line: not available [native method]  

I am trying to create a plugin for the libPD library to work with android and therefore I need the above to work corectly in order to proceed any further.

1

There are 1 answers

0
Sahil On

I found the answer of this and I thought I would post it so it might be useful for someone in the future.

cordova.getActivity().getResources() was set to null (don't know how) inside loadPatch method when I debugged the code line by line. therefore what I did was that I passed applicationContext as parameter to the loadPatch method.

private void loadPatch(Context ctx) throws IOException { 
   //CODE HERE
}

I was calling loadPatch method from the execute method of the class where the cordova.getActivity().getApplicationContext() was not null so I called loadPatch method like the following.

AppContext = this.cordova.getActivity().getApplicationContext();
this.loadPatch(this.AppContext);