Search code examples
androidfilemethodsstatic

Why can't I use getFilesDir(); in a static context?


I have looked everywhere for an answer and every time I see someone else use the method:

getFilesDir();

But when I try and use that method in any way, especially:

File myFile = new File (getFilesDir();, filename );

Eclipse just says, "Cannot make static reference to non-static method getFilesDir from tye ContextWrapper"

I am trying to use it to get the internal directory to write a file for my application.

Thanks!


Solution

  • That is because in the static method you have not got the object of the class and getFilesDir is not a static method that means it will only be accessible via the object of class Context.

    So what you can do is store the reference to the object in a static variable of your class and then use that in your static method.

    for example:

    static YourContextClass obj;
    
    static void method(){
       File myFile = new File (obj.getFilesDir(), filename );
    }
    

    also you will have to store the reference to the object in your onCreateMethod()

     obj = this;
    

    The best way to achieve this is

     static void method(YourContextClass obj){
          File myFile = new File (obj.getFilesDir(), filename );
     }