Volley AppController class object returning null

前端 未结 4 1746
温柔的废话
温柔的废话 2021-01-19 12:46

I am making an app that makes a JsonObjectRequest and retrieves a JSON data from an URL using the Volley Networking Library for android.

AppCon

4条回答
  •  盖世英雄少女心
    2021-01-19 13:07

    i think you should create the "AppController" like this :

    public class AppController {
    
        private static AppController mInstance;
    
        private RequestQueue mRequestQueue;
    
        private static Context mCtx;
    
        private AppController(Context context){
            mCtx = context;
            mRequestQueue = getRequestQueue();
        }
    
        public static synchronized AppController getInstance(Context context) {
            if (mInstance == null) {
                mInstance = new AppController(context);
            }
            return mInstance;
        }
    
        public RequestQueue getRequestQueue() {
            if (mRequestQueue == null) {
                mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
            }
            return mRequestQueue;
        }
    
        public  void addToRequestQueue(@NonNull final Request request) {
            getRequestQueue().add(request);
        }
    
        public  void addToRequestQueueWithTag(@NonNull final Request request, String tag) {
            request.setTag(tag);
            getRequestQueue().add(request);
        }
    }
    

    and the MainActivity.class

    //adding request to the RequestQueue
    AppController.getInstance(this).addToRequestQueue(jsonObjReq);
    

提交回复
热议问题