Reputation:
with android Volley
tutorials i'm creating simple single Singleton class as an Volley, but after prepare GET and POST method i get NullPointerException
error and i can not find whats error:
AppControllert Volley
singleton class:
public class ApplicationController extends Application {
public static final String TAG = "VolleyPatterns";
private RequestQueue mRequestQueue;
private static ApplicationController sInstance;
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static synchronized ApplicationController getInstance() {
return sInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
VolleyLog.e("Adding request to queue: %s", req.getUrl());
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
and in Activity i'm try to create simple request with this class:
final String URL = "http://192.168.1.6/apitest";
JsonObjectRequest req = new JsonObjectRequest(URL, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e("Response:", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
}
});
ApplicationController.getInstance().addToRequestQueue(req);
Logcat error:
Caused by: java.lang.NullPointerException
at asrebidaree.ir.asrebidaree.ActivityRegistration.onCreate(ActivityRegistration.java:37)
Line 37 is : ApplicationController.getInstance().addToRequestQueue(req);
Upvotes: 1
Views: 4196
Reputation: 157487
The code looks good. You have to register your Application's subclass in your AndroidManifest.xml
. If you didn't, your sInstance
will not be initialized, since Android will not use your Application's sublcass
Upvotes: 3