Volley抛出异常onBackPressed?

时间:2015-03-03 18:15:32

标签: android android-volley

我正在使用Volley API来使用Web服务。它工作正常,但当我按下设备后退按钮时会抛出异常NullPointerException并停止应用程序。我认为这个问题是因为有一个待处理的请求,但我无法解决它。我尝试在cancelPendingRequests中使用onBackPressed,但仍然不起作用。

我该怎么解决?

Volley Singleton

public class CustomVolleySingleton extends Application{

    private static CustomVolleySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    public static final String TAG = "VolleyPatterns";

    private CustomVolleySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap>
                    cache = new LruCache<String, Bitmap>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }

    public static synchronized CustomVolleySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new CustomVolleySingleton(context);
        }
        return mInstance;
    }

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

    public <T> void addToRequestQueue(Request<T> req) {
        req.setRetryPolicy(new DefaultRetryPolicy(
                           120000,
                           DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                           DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

onBackPressed

@Override
    public void onBackPressed() {
           CustomVolleySingleton.getInstance(getApplicationContext()).cancelPendingRequests(CustomVolleySingleton.TAG);
            super.onBackPressed();

    }

异常

03-03 15:28:48.689  24175-24175/br.com.myapp.batalhajuridica E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: br.com.myapp.batalhajuridica, PID: 24175
    java.lang.NullPointerException
            at br.com.myapp.batalhajuridica.frags.JogosAbertosFrag$1.getListBatalhaAbertaFechada(JogosAbertosFrag.java:121)
            at br.com.myapp.batalhajuridica.dao.BatalhaDAO$5.onResponse(BatalhaDAO.java:206)
            at br.com.myapp.batalhajuridica.dao.BatalhaDAO$5.onResponse(BatalhaDAO.java:136)
            at br.com.myapp.batalhajuridica.cv.ApplicationController.deliverResponse(ApplicationController.java:81)
            at br.com.myapp.batalhajuridica.cv.ApplicationController.deliverResponse(ApplicationController.java:28)
            at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)

4 个答案:

答案 0 :(得分:4)

这是一个很好的SingletonClass来玩排球

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static AppController mAppController;

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

    //Getting App Controller Instance
    public static synchronized AppController getInstance()
    {
        Log.d("X","AppController Instance Passed");
        return mAppController;
    }

    //Getting Request Queue
    public RequestQueue getRequestQueue()
    {
        Log.d("X","Request que passed");
        if(mRequestQueue==null)
        {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    //Getting image Loader
    public ImageLoader getImageLoader()
    {
        Log.d("X","ImageLoader passed");
        getRequestQueue();
        if(mImageLoader==null)
        {
            mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    //Adding to requestque with tag
    public <T> void addToRequestQueue(Request<T> req,String tag)
    {   
        Log.i("X","Added to Request Que");
        req.setTag(TextUtils.isEmpty(tag)? TAG : tag);
        getRequestQueue().add(req);
    }

    //Adding to Request que without custom tag
    public <T> void addToRequestQueue(Request<T> req)
    {
        Log.i("X","Added to Request Que");
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(String tag)
    {
        if(mRequestQueue!=null)
        {
            mRequestQueue.cancelAll(tag);
        }
    }


}

LruBitmapCache.java

public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageCache {

    //Getting cache size    
    public static int getDefaultLruCacheSize() {
        Log.d("X","Cache size provided");
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;

        return cacheSize;
    }

    //No parm Constructor
    public LruBitmapCache()
    {
        //Calling second constructor
        this(getDefaultLruCacheSize());
    }

    //Second Constructor
    public LruBitmapCache(int maxSize) {
        super(maxSize);
    }


    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }


}

并像这样使用

//Volley JSONArrayRequest
        JsonArrayRequest mJsonArrayRequest = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {

                //Play with the JSONArray response here

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError err) {
                //Handle the error here
            }

        });

        //Adding to Queue
        AppController.getInstance().addToRequestQueue(mJsonArrayRequest);

答案 1 :(得分:2)

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mAppController;

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

//Getting App Controller Instance
public static synchronized AppController getInstance()
{
    Log.d("X","AppController Instance Passed");
    return mAppController;
}

//Getting Request Queue
public RequestQueue getRequestQueue()
{
    Log.d("X","Request que passed");
    if(mRequestQueue==null)
    {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

//Getting image Loader
public ImageLoader getImageLoader()
{
    Log.d("X","ImageLoader passed");
    getRequestQueue();
    if(mImageLoader==null)
    {
        mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
    }
    return this.mImageLoader;
}

//Adding to requestque with tag
public <T> void addToRequestQueue(Request<T> req,String tag)
{   
    Log.i("X","Added to Request Que");
    req.setTag(TextUtils.isEmpty(tag)? TAG : tag);
    getRequestQueue().add(req);
}

//Adding to Request que without custom tag
public <T> void addToRequestQueue(Request<T> req)
{
    Log.i("X","Added to Request Que");
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(String tag)
{
    if(mRequestQueue!=null)
    {
        mRequestQueue.cancelAll(tag);
    }
}

} 和LruBitmapCache.java

public class LruBitmapCache extends LruCache实现了ImageCache {

//Getting cache size    
public static int getDefaultLruCacheSize() {
    Log.d("X","Cache size provided");
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;

    return cacheSize;
}

//No parm Constructor
public LruBitmapCache()
{
    //Calling second constructor
    this(getDefaultLruCacheSize());
}

//Second Constructor
public LruBitmapCache(int maxSize) {
    super(maxSize);
}


@Override
protected int sizeOf(String key, Bitmap value) {
    return value.getRowBytes() * value.getHeight() / 1024;
}

@Override
public Bitmap getBitmap(String url) {
    return get(url);
}

@Override
public void putBitmap(String url, Bitmap bitmap) {
    put(url, bitmap);
}

} 并像这样使用

// Volley JSONArrayRequest         JsonArrayRequest mJsonArrayRequest = new JsonArrayRequest(URL,new Response.Listener(){

        @Override
        public void onResponse(JSONArray response) {

            //Play with the JSONArray response here

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError err) {
            //Handle the error here
        }

    });

    //Adding to Queue
    AppController.getInstance().addToRequestQueue(mJsonArrayRequest);

答案 2 :(得分:1)

看看这个

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static AppController mAppController;

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

    //Getting App Controller Instance
    public static synchronized AppController getInstance()
    {
        Log.d("X","AppController Instance Passed");
        return mAppController;
    }

    //Getting Request Queue
    public RequestQueue getRequestQueue()
    {
        Log.d("X","Request que passed");
        if(mRequestQueue==null)
        {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    //Getting image Loader
    public ImageLoader getImageLoader()
    {
        Log.d("X","ImageLoader passed");
        getRequestQueue();
        if(mImageLoader==null)
        {
            mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    //Adding to requestque with tag
    public <T> void addToRequestQueue(Request<T> req,String tag)
    {   
        Log.i("X","Added to Request Que");
        req.setTag(TextUtils.isEmpty(tag)? TAG : tag);
        getRequestQueue().add(req);
    }

    //Adding to Request que without custom tag
    public <T> void addToRequestQueue(Request<T> req)
    {
        Log.i("X","Added to Request Que");
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(String tag)
    {
        if(mRequestQueue!=null)
        {
            mRequestQueue.cancelAll(tag);
        }
    }


}

答案 3 :(得分:0)

喜欢这个

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static AppController mAppController;

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

    //Getting App Controller Instance
    public static synchronized AppController getInstance()
    {
        Log.d("X","AppController Instance Passed");
        return mAppController;
    }

    //Getting Request Queue
    public RequestQueue getRequestQueue()
    {
        Log.d("X","Request que passed");
        if(mRequestQueue==null)
        {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    //Getting image Loader
    public ImageLoader getImageLoader()
    {
        Log.d("X","ImageLoader passed");
        getRequestQueue();
        if(mImageLoader==null)
        {
            mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    //Adding to requestque with tag
    public <T> void addToRequestQueue(Request<T> req,String tag)
    {   
        Log.i("X","Added to Request Que");
        req.setTag(TextUtils.isEmpty(tag)? TAG : tag);
        getRequestQueue().add(req);
    }

    //Adding to Request que without custom tag
    public <T> void addToRequestQueue(Request<T> req)
    {
        Log.i("X","Added to Request Que");
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(String tag)
    {
        if(mRequestQueue!=null)
        {
            mRequestQueue.cancelAll(tag);
        }
    }


}