使用android Volley
教程我正在创建简单的Singleton类作为Volley,但在准备好GET和POST方法后我得到NullPointerException
错误,我找不到什么错误:
AppControllert Volley
单身人士课程:
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);
}
}
}
在Activity中我尝试用这个类创建简单的请求:
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错误:
Caused by: java.lang.NullPointerException
at asrebidaree.ir.asrebidaree.ActivityRegistration.onCreate(ActivityRegistration.java:37)
第37行是:ApplicationController.getInstance().addToRequestQueue(req);
答案 0 :(得分:2)
代码看起来不错。您必须在AndroidManifest.xml
中注册您的应用程序的子类。如果您没有,则sInstance
将不会被初始化,因为Android不会使用您的应用程序的sublcass