发出 Volley-okhttp 请求时出现 NullPointerException

NullPointerException when making Volley-okhttp request

我正在尝试将 Google Volley 与 okHttp 结合使用。我按照本教程 http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ 来设置所有内容。我设置了 volley 单例和 LruBitmapCache。使用了他们的 get string 请求,但每次我发出请求时,我都会收到 NullPointerException。

7717-8280/com.admin.zipline E/AndroidRuntime﹕ FATAL EXCEPTION: pool-9-thread-1
Process: com.admin.zipline, PID: 7717
java.lang.NullPointerException
        at com.admin.zipline.activities.AccountVerification.getTransactionsDetails(AccountVerification.java:295)
        at com.admin.zipline.activities.AccountVerification_.access1(AccountVerification_.java:25)
        at com.admin.zipline.activities.AccountVerification_.execute(AccountVerification_.java:203)
        at org.androidannotations.api.BackgroundExecutor$Task.run(BackgroundExecutor.java:302)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access1(ScheduledThreadPoolExecutor.java:152)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)

这是我的要求

错误在第 295 行,即 VolleyNetwork.getInstance().addToRequestQueue(strReq, tag_string_req);

@Background
public void getTransactionsDetails() {

String url = NetworkConstants.Url_transactions;
// Tag used to cancel the request
String  tag_string_req = "string_req";
Log.i("URL",url);
StringRequest strReq = new StringRequest(Request.Method.GET,
        url, new Response.Listener<String>() {

    @Override
    public void onResponse(String response) {
        Log.i("Response", response.toString());

    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        Log.i("Error", "Error: " + error.getMessage());
    }
}){
   /**
    ** Passing some request headers
    * */
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", VolleyNetwork.authorization);
        return headers;
    }
};

// Adding request to request queue
if(VolleyNetwork.getInstance() == null){
    Log.i("NULL", "NETWORK NULL");
}else {
    VolleyNetwork.getInstance().addToRequestQueue(strReq, tag_string_req);
}

}

除了在顶部添加了一些全局变量之外,我的单例设置几乎完全相同。

VolleyNetwork.java

public class VolleyNetwork extends Application {
Context context;
public static String access_token,token_type,user_id,name, authorization;
public VolleyNetwork(Context context) {
    this.context = context;
    SharedPreferences preferences = context.getSharedPreferences(FileNames.login_details, Context.MODE_PRIVATE);
    access_token = preferences.getString(NetworkConstants.acess_token, "");
    token_type = preferences.getString(NetworkConstants.token_type, "");
    user_id = preferences.getString(NetworkConstants.user_id, "");
    authorization = token_type + " " + access_token;
}

public static final String TAG = VolleyNetwork.class
        .getSimpleName();

private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

private static VolleyNetwork mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized VolleyNetwork getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public ImageLoader getImageLoader() {
    getRequestQueue();
    if (mImageLoader == null) {
        mImageLoader = new ImageLoader(this.mRequestQueue,
                new LruBitmapCache());
    }
    return this.mImageLoader;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    // set the default tag if tag is empty
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    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);
    }
}

}

我想这可能与我的清单有关。我不太确定如何设置它。我之前的人设置了大部分应用程序,我对 Java.

不是很熟悉

现在清单使用 android.permission.INTERNET permission,应用程序的名称是 .activities.MyApplication。 MyApplication 扩展应用程序。我尝试将应用程序名称设置为 .network.VolleyNetwork,并让 VolleyNetwork 扩展 MyApplication,但得到 "VolleyNetwork has no default constructor."

不太确定在这里做什么。

发生这种情况是因为您实际上并未创建对象 VolleyNetwork。

单例模式是这样工作的:

public class MySingleton {
    private static MySingleton instance;
    private MySingleton(){
        //constructor here
    }
    public static MySingleton getInstance(){
        if(instance==null){
            instance = new MySingleton();
        }
        return instance;
    }
}

请注意,静态 getInstance 方法实际上会创建您的实例并确保它存储在静态字段中,而在您的情况下它会检索默认值 null。

此外,确保将构造函数设为私有,这样实例只能通过 public getInstance 方法检索,否则任何人都可以调用构造函数并创建尽可能多的实例一个感觉。