Skip to content Skip to sidebar Skip to footer

Do Android Volley Have Callback Do Something Like Java Finally?

I have to do something after the request finish. like dismiss a loading dialog I have to add dialog.dismiss(); in every request for both onResponse() and onErrorResponse(). Do voll

Solution 1:

Yes you can do this by creating custom volley request. See the code below :

import java.io.UnsupportedEncodingException;
import java.util.Map;    
import org.json.JSONException;
import org.json.JSONObject;    
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import android.app.AlertDialog;

publicclassCustomRequestextendsRequest<JSONObject> {
    privateListener<JSONObject> listener;
    privateMap<String, String> params;
    privateAlertDialog dialog;

 //You can replace AlertDialog by the Type of dialog you usepublicCustomRequest(String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener          errorListener,AlertDialog dialog)
          {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
        this.dialog =dialog;
    }
    publicCustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }
    protectedMap<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    }; 

    @OverrideprotectedResponse<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            //Here you can call dialog.dismiss();
            dialog.dismiss();
            String jsonString = newString(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            returnResponse.success(newJSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            returnResponse.error(newParseError(e));
        } catch (JSONException je) {
            returnResponse.error(newParseError(je));
        }
    }
    @OverrideprotectedvoiddeliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}
}

Let me know if this works. :)

Post a Comment for "Do Android Volley Have Callback Do Something Like Java Finally?"