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
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);
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"/>
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.
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);
}