我试图按照this guide关于如何使用Singleton与Volley一起工作.目标是使用此Singleton将我的RequestQueue放在Application上下文中,这样它就不会受到从landscape到portrait等的影响.
但是我收到以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method ‘java.io.file androID.content.Context.getCacheDir()’ on a null object reference
at com.androID.volley.toolBox.Volley.newRequestQueue(Volley.java:45)
at 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)
at 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 LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(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中的一行代码在异常中提到:
file cacheDir = new file(context.getCacheDir(), DEFAulT_CACHE_DIR);
我需要帮助才能传递此错误.
解决方法:
如果您阅读了代码链接到的Github repo的自述文件,具体提到,则需要将其添加到清单XML中.
<application androID:name="com.company.MyApplication"></application>
在您的情况下,将com.company.MyApplication更改为xxx.yyy.HelperApplication.
总结以上是内存溢出为你收集整理的java – 使用Singleton模式的Android Volley错误全部内容,希望文章能够帮你解决java – 使用Singleton模式的Android Volley错误所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)