排球教程 - getCacheDir() - 无法解析方法

时间:2016-01-13 17:10:32

标签: java android android-volley

在此链接中: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;

1 个答案:

答案 0 :(得分:1)

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

使用NetworkActivity类构造函数获取Context:

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()