我正在尝试按照本指南使用Singleton如何使用Volley.目标是使用此Singleton将我的RequestQueue放在Application上下文中,这样它就不会受到从landscape到portrait等的影响.
但是我收到以下错误:
java.lang.NullPointerException:尝试在com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:45)上的空对象引用上调用虚方法'java.io.File android.content.Context.getCacheDir()' )com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:105)at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:115)at se.ccconsulting.arenaui3.VolleySingleton.(VolleySingleton) .java:20)在se.ccconsulting.arenaui3.VolleySingleton.getInstance(VolleySingleton.java:34)at se.ccconsulting.arenaui3.AdventureFragment.onCreateView(AdventureFragment.java:62)...
它指向这一行:
mRequestQueue = Volley.newRequestQueue(HelperApplication.getAppContext());
我不确定这里有什么问题,因为我在代码中可以看到VolleySingleton.java中的getInstance()方法不应该
VolleySingleton.java
public class VolleySingleton { private static VolleySingleton mInstance = null; private RequestQueue mRequestQueue; private ImageLoader mImageLoader; private VolleySingleton(){ mRequestQueue = Volley.newRequestQueue(HelperApplication.getAppContext()); mImageLoader = new ImageLoader(this.mRequestQueue, new ImageLoader.ImageCache() { private final LruCachemCache = new LruCache (10); public void putBitmap(String url, Bitmap bitmap) { mCache.put(url, bitmap); } public Bitmap getBitmap(String url) { return mCache.get(url); } }); } public static VolleySingleton getInstance(){ if(mInstance == null){ mInstance = new VolleySingleton(); } return mInstance; } public RequestQueue getRequestQueue(){ return this.mRequestQueue; } public ImageLoader getImageLoader(){ return this.mImageLoader; } }
HelperApplication.java
public class HelperApplication extends Application{ private static HelperApplication mInstance; private static Context mAppContext; @Override public void onCreate() { super.onCreate(); mInstance = this; this.setAppContext(getApplicationContext()); } public static HelperApplication getInstance(){ return mInstance; } public static Context getAppContext() { return mAppContext; } public void setAppContext(Context mAppContext) { this.mAppContext = mAppContext; } }
这是我在实施Singlton之前从Volley使用的代码行,它完美地工作但不满足我的需求:
RequestQueue queue = Volley.newRequestQueue(getActivity());
我在Genymotion上调试.Fruthermore,Volley.java中的一行代码在异常中提到:
文件cacheDir = new File(context.getCacheDir(),DEFAULT_CACHE_DIR);
我需要帮助才能传递此错误.
如果您阅读了代码链接到的Github repo的README ,它特别提到,您需要将它添加到清单XML中.
在你的情况下,更改com.company.MyApplication
到xxx.yyy.HelperApplication
,虽然.