Android创建简单的凌空Singleton类来准备GET和POST方法

时间:2015-09-26 12:26:49

标签: android android-volley

使用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);

1 个答案:

答案 0 :(得分:2)

代码看起来不错。您必须在AndroidManifest.xml中注册您的应用程序的子类。如果您没有,则sInstance将不会被初始化,因为Android不会使用您的应用程序的sublcass