Volley 教程 - getCacheDir() - 无法解析方法

Volley Tutorial - getCacheDir() - Cannot resolve method

在此 link 中:http://developer.android.com/training/volley/requestqueue.html

标题:设置网络和缓存

它这样定义缓存:

Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024);

我现在搜索了 30 分钟,我尝试导入 android.content.Context 但仍然出现错误:无法解析方法。

我的代码:

class NetworkActivity{
String url;

RequestQueue networkRequest;
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
...

我不知道我是否扩展了一些东西,因为它在示例中什么也没说。

这是我的导入:

import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;

getCacheDir 方法来自 Context class 因此您需要使用有效的 Context 才能访问它。

使用NetworkActivityclass构造函数获取上下文:

public class NetworkActivity{
    private Context mContext;
    Cache cache;
    NetworkActivity(Context mContext){
        this.mContext=mContext;
        this.cache = new DiskBasedCache(mContext.getCacheDir(), 1024 * 1024);
    }
}

像使用 Activity 一样传递上下文:

NetworkActivity objNetworkActivity=new NetworkActivity(ClassName.this);

或者如果使用 Fragment 则使用 getActivity().