简体   繁体   English

无法在 Android Studio 中找到 getExternalFilesDir() 函数的上下文

[英]Unable to find Context for getExternalFilesDir() function in Android Studio

So, I am trying to write text to a file in Android Studio.所以,我正在尝试将文本写入 Android Studio 中的文件。 I have the following code:我有以下代码:

public void sampleFunction() {
    File file = new File(getExternalFilesDir(null), "sample-file.txt");
}

The issue is that the method getExternalFilesDir(null) cannot be resolved.问题是方法 getExternalFilesDir(null) 无法解析。 After doing some research I have noted that I need to provide the Context class.在做了一些研究之后,我注意到我需要提供 Context 类。 Such as:如:

public void sampleFunction(Context c) {
    File file = new File(c.getExternalFilesDir(null), "equation_history.xml");
}

And when I called sampleFunction, I would simply pass in the current Context:当我调用 sampleFunction 时,我会简单地传入当前上下文:

sampleFunction(this);

This normally would work, however, I need to call this function inside a setOnClickListener function for a Button.这通常会起作用,但是,我需要在按钮的 setOnClickListener 函数中调用此函数。 For example:例如:

Button b_go = findViewById(R.id.b_go);
b_go.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Functions.sampleFunction(this);
    }
});

So the return value for this is android.view.View.OnClickListener rather than android.content.Context .所以它的返回thisandroid.view.View.OnClickListener而不是android.content.Context

How might I get around this?我该如何解决这个问题? Any advice would be greatly appreciated.任何建议将不胜感激。

Instead of passing "this" as an argument try calling getApplicationContext() or if you are in fragment just call getActivity().不要将“this”作为参数传递,而是尝试调用 getApplicationContext(),或者如果您在片段中,则只需调用 getActivity()。

What is often done is that a Context myContext variable is declared in the class, then onCreate, you populate it with myContext = this;经常做的是在类中声明一个 Context myContext 变量,然后 onCreate,你用 myContext = this; 填充它; Then, in any listener or Async Task, you can use myContext.getExternalFilesDir(null)然后,在任何侦听器或异步任务中,您可以使用 myContext.getExternalFilesDir(null)

File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM