【问题标题】:Why can't I use getFilesDir(); in a static context?为什么我不能使用 getFilesDir();在静态环境中?
【发布时间】:2013-03-24 22:59:09
【问题描述】:

我到处寻找答案,每次看到其他人使用该方法时:

getFilesDir();

但是当我尝试以任何方式使用该方法时,尤其是:

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

Eclipse 只是说,“不能从 ContextWrapper 对非静态方法 getFilesDir 进行静态引用”

我正在尝试使用它来获取内部目录来为我的应用程序编写文件。

谢谢!

【问题讨论】:

  • 你通过使用名称和目录获取文件节省了我的时间:)

标签: android file methods static


【解决方案1】:

我要谈谈发生在我身上的事情。我正在开发一个日志系统文件,所以我创建了一个新类,我想为我的所有应用程序和这个类的许多实例做不同的日志。所以我想在类似于单例类的应用程序类上创建我的类的受保护或公共对象。

所以我有类似的东西:

      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 错误。 这种情况下的解决方案非常简单,让我同时感到笨拙和自豪。

我无法在 MyApp 的声明空间中调用 getFilesDir,因为此时没有获取该 Dir 的上下文。 Android App 中的执行顺序是:Application --> Activity。就像 Manifest 文件中所说的那样。

解决方案?在 MyApp 类的 onCreate 事件中创建我的对象,如下所示:

    public class MyApp extends Application {
        protected LogApp logApp; 

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

所以现在我可以在我的主类中以同样的方式使用它,因为我的 MainActivity 的一个实例在上下文类的最后一个实例中扩展。

也许我对可能的解释有误,这不是真正发生的术语含义以及 android 的工作原理。如果有人比我更了解为什么会这样,我邀请您消除我们的疑虑。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    那是因为在静态方法中你没有得到类的对象,而 getFilesDir 不是静态方法,这意味着它只能通过类 Context 的对象访问。

    所以你可以做的是将对象的引用存储在你的类的静态变量中,然后在你的静态方法中使用它。

    例如:

    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 );
     }
    

    【讨论】:

    • 嗯,现在调用时会报NullPointerException?
    • 就是现在编译了但是调用的时候崩溃了。
    • 你在创建Activity之前调用了这个方法吗?在 Oncreate 方法中,对象需要被初始化..
    • 嗯,是的,它是在 onCreate() 之前调用的,我可以移动 obj = this;到它自己的方法或另一个类(这个方法是从一个不同的类调用的)
    • 如果其他类是 Context 的派生类,即 Activity,然后您可以在方法中传递该类的对象并使用它的方法...请参阅我的更新答案,这也是最好的方法
    猜你喜欢
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 2021-04-20
    • 2010-10-20
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    相关资源
    最近更新 更多