java - Volley 请求队列返回 null

标签 java android json networking android-volley

这是我的单例类:

public class RequestSingleton {

    private static RequestSingleton mInstance ;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

        private RequestSingleton(Context context){
            mCtx = context;
            mRequestQueue = getRequestQueue();

            mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache(){

                private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);

                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }

                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            });
        }

    public static synchronized RequestSingleton getInstance(Context context){
        if (mInstance == null){
            mInstance = new RequestSingleton(context);
        }
        return mInstance;
    }

    private RequestQueue getRequestQueue(){
        if(mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req){
        getRequestQueue().add(req);
    }
    public ImageLoader getImageLoader(){
        return mImageLoader;
    }

这是主 Activity 中获取帖子的方法:

public void getJsonPosts(){

        String url = "http://linagrey.blogspot.com/feeds/posts/default?alt=json";


        JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject feedResponse =  response.getJSONObject("feed");
                    JSONArray entryArrayPosts = feedResponse.getJSONArray("entry");
                    BlogPost bp;
                    for (int i = 0; i < entryArrayPosts.length(); i++){
                        bp = new BlogPost();
                        //Get the entry as an array and loop through
                        JSONObject entryBlogPost = entryArrayPosts.getJSONObject(i);

                        //Get the title from the array
                        JSONObject postObject = entryBlogPost.getJSONObject("title");
                        //JSONObject postHtmlContent = entryBlogPost.getJSONObject(KEYS.POST_JSON_OBJECT_HTML_CONTENT);

                        //GET LINK ARRAY FROM JSON
                        JSONArray linkAddress = entryBlogPost.getJSONArray(KEYS.POST_JSON_ARRAY_OBJECT);

                        if(entryBlogPost.has(KEYS.MEDIA_THUMBNAIL)) {
                            JSONObject imageObjectUrl = entryBlogPost.getJSONObject(KEYS.MEDIA_THUMBNAIL);
                            String thumbnailUrl = imageObjectUrl.getString(KEYS.MEDIA_THUMBNAIL_URL);
                            bp.setmUrlThumbnail(thumbnailUrl);
                        }

                        //for loop for link array object
                        for (int j = 0;j < linkAddress.length(); j++){
                            JSONObject eachLink = linkAddress.getJSONObject(4);
                            String htmlUrl = eachLink.getString(KEYS.POST_HTML_LINK);
                            bp.setmLinkContent(htmlUrl);
                        }


                        //Get title string contained in Title Object
                        String title = postObject.getString(KEYS.POST_TITLE);
                        Log.v(TAG, "OBJECTS HAVE THIS PROPERTIES: " + i + " " + title);


                        //Set Properties Gotten
                        bp.setmTitle(title);

                        Log.v(TAG, "OBJECTS HAVE THIS PROPERTIES: " + i + " " + bp.toString());
                        //Add a blog post Object to the Arraylist
                        postArrayList.add(bp);


                    }
                   // Log.v(TAG, "Arraylist SIZE " + postArrayList.size());

                    for(BlogPost posts : postArrayList){
                        Log.v(TAG, posts + " ");
                    }

                    // Toast.makeText(this.,response.toString(),Toast.LENGTH_LONG).show();

                }catch(JSONException e){
                    Log.v(TAG, e.toString());
                }
            }
        },new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.v(TAG, error.toString());
            }
        });
        RequestSingleton.getInstance(this).addToRequestQueue(jsonRequest);
     }

这是错误输出,我不知道如何解释这些错误消息:

05-31 08:44:14.880 2653-2653/wait.com.linasblog E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: wait.com.linasblog, PID: 2653
                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{wait.com.linasblog/wait.com.linasblog.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                      at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
                                                                      at wait.com.linasblog.RequestSingleton.getRequestQueue(RequestSingleton.java:51)
                                                                      at wait.com.linasblog.RequestSingleton.<init>(RequestSingleton.java:24)
                                                                      at wait.com.linasblog.RequestSingleton.getInstance(RequestSingleton.java:44)
                                                                      at wait.com.linasblog.MainActivity.getJsonPosts(MainActivity.java:204)
                                                                      at wait.com.linasblog.MainActivity.onCreate(MainActivity.java:41)
                                                                      at android.app.Activity.performCreate(Activity.java:6237)
                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                      at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                      at android.os.Looper.loop(Looper.java:148) 
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                      at java.lang.reflect.Method.invoke(Native Method) 
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

我之前发布了类似的问题,但尚未得到答案。

最佳答案

我认为请求单例类没有被初始化。所有字段都是静态的,但它们尚未设置为任何内容,因此它们仍然为空。在尝试添加到请求队列之前,请尝试 RequestSingleton rs = new RequestSingleton();。更好的是覆盖应用程序类,以便它在启动时初始化请求单例类。

编辑: 我不知道这是否是最佳实践,但如果您仍然遇到问题,至少可以尝试其他方法。这将覆盖应用程序类并使用自定义类。当您的应用程序启动时,它将初始化 Volley。

public class VolleyApplication extends Application {
    private static final String TAG = VolleyNetworkTask.class.getSimpleName();
    private static VolleyNetworkTask sInstance;
    private static RequestQueue mRequestQueue;

    @Override
    public void onCreate() {
        super.onCreate();
        mRequestQueue = Volley.newRequestQueue(this);
        sInstance = this;
    }

    public synchronized static VolleyNetworkTask getInstance() {
        return sInstance;
    }

    public static RequestQueue getRequestQueue() {
        return mRequestQueue;
    }
}

并将其放入 list 标签中的 list 中

    <application 
        android:name=".VolleyApplication"
        .../>

获取请求队列 VolleyApplication.getRequestQueue();

关于java - Volley 请求队列返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37548927/

相关文章:

sql - 在 Snowflake 中解析 JSON

java - 更改 JSlider 上旋钮的宽度

java - Android:查看连接到我的wifi的所有设备

android - 如何以编程方式 'restart' android 应用程序

android - ondestroy不总是被调用吗?

android - 我想在 android 应用程序中发布 geosever 层,使用 arcgis SDK,我已经完成了代码但它不起作用,请告诉我我做错了什么?

javascript - 在 JavaScript 中加载

php json_encode 部分不适用于数组

java - 使用java创建分层json

java - 如何将扁平化的 LinkedHashMap 转换为表示层次结构的 LinkedHashMap