Volley AppController class object returning null

前端 未结 4 1745
温柔的废话
温柔的废话 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 <T> void addToRequestQueue(@NonNull final Request<T> request) {
            getRequestQueue().add(request);
        }
    
        public <T> void addToRequestQueueWithTag(@NonNull final Request<T> request, String tag) {
            request.setTag(tag);
            getRequestQueue().add(request);
        }
    }
    

    and the MainActivity.class

    //adding request to the RequestQueue
    AppController.getInstance(this).addToRequestQueue(jsonObjReq);
    
    0 讨论(0)
  • 2021-01-19 13:09

    Your AppController class needs to extend Application class instead of the AppCompatActivity class.

    And remember to update your Manifest as well. ie. Add this class in your AndroidManifest.xml using name attribute for <application> tag.

    <application
            android:name=".AppController"/>
    
    0 讨论(0)
  • 2021-01-19 13:09

    you can't use an Activity like a Singleton. An Activity is a screen of your app and it could be in different states during the usage of your app. You are also leaking it, since you keep a static reference to it. For your purpose, if you need a Context, extend Application instead of AppCompatActivity, and register it in your Manifest.

    0 讨论(0)
  • 2021-01-19 13:23

    Don't you forget to initialize the RequestQueue Object. You need to initialize the RequestQueue inside the onCreate method, like you can see in the example:
    (Else when you call request.add(jsonObjectRequest) the application will try to reference the null object)

    RequestQueue request;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //request qwe
        request= Volley.newRequestQueue(this);
    }
    
    0 讨论(0)
提交回复
热议问题