在发出Volley-okhttp请求时出现NullPointerException

时间:2015-05-29 15:34:16

标签: java android android-volley okhttp

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

 <?php
    $angka = array(1,11,12,13,2,21,22,23);

    echo "<ul>";
    $counter = 0;
    foreach($angka as $value){
        $quotient = $value / 10;

        if ($quotient == 0) { // Meaning not - sub
            echo "<li>ini bukan sub</li>";  
            $counter = 0; // reset sub - index
        }
        else { // Display subs
            switch ($counter) { //Select what sub type to be displayed
                case 0: // first sub
                    echo "<li><ul>";
                    echo "<li>ini buka sub</li>";   
                    break;
                case 1: //second sub
                    echo "<li>ini sub tengah</li>";
                case 2: //third sub
                    echo "<li>ini sub akhir</li>";
                    echo "</ul></li>";
            }
            $counter++;
        }
    }
echo "</ul>";

这是我的要求

错误在第295行,即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_.access$701(AccountVerification_.java:25) at com.admin.zipline.activities.AccountVerification_$8.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.access$201(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)

VolleyNetwork.getInstance().addToRequestQueue(strReq, tag_string_req);

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

VolleyNetwork.java

@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);
}

}

我认为这可能与我的清单有关。我真的不确定如何设置它。我之前的人设置了大部分应用程序,而且我对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); } } } ,应用程序的名称为android.permission.INTERNET permission。 MyApplication扩展了Application。我尝试将应用程序名称设置为.activities.MyApplication,并让VolleyNetwork扩展MyApplication,但得到“VolleyNetwork没有默认构造函数。”

不确定在这做什么。

1 个答案:

答案 0 :(得分:1)

这是因为你实际上并没有创建你的对象,VolleyNetwork。

Singleton模式的工作原理如下:

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。

此外,请确保将构造函数设为私有,以便只能通过公共getInstance方法检索实例,否则任何人都可以调用构造函数并创建尽可能多的实例。