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

I searched everywhere for an answer and every time I see someone using this method:

getFilesDir();

But when I try to use this method in any way, especially:

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

Eclipse simply says: "It is not possible to make a static reference to the non-static getFilesDir method from tye ContextWrapper"

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

Thank!

+5
source share
2 answers

This is because in the static method you do not have a class object, and getFilesDir is not a static method, which means that it will be available only through the object of the Context class.

, , , .

:

static YourContextClass obj;

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

onCreateMethod()

 obj = this;

-

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

, . , , , , . , .

, - :

      public class MyApp extends Application {
        protected LogApp logApp = new LogApp(getFilesDir());

, , :

      public class LogApp {
         public File dirFiles;

         //file parameter can't be null, the app will crash
         public LogApp(File file){
            dirFiles = file;
         }

         public File[] getListFiles(){
            return dirFiles.listFiles()
         }

      public class MainActivity extends AppCompatActivity {
         protected void onCreate(Bundle savedInstanceState) {
            MyApp myApp = (MyApp)getApplicationContext();
            File file[] = myApp.logApp.getListFiles();
      }

nullPointException. , .

getFilesDir MyApp, Dir. Android-: Application → Activity. .

? onCreate MyApp, :

    public class MyApp extends Application {
        protected LogApp logApp; 

        void onCreate(){
           logApp = new LogApp(getFilesDir());

, , , MainActivity, .

, , , . - , , .

, .

+1

All Articles