I decided to give Volley a try, so presently I have a lot of REST callouts to be done, so I usually create a RequestHandler and a ResponseHandler class which as their names sugg
This works for me.
Map<String, String> params = new HashMap<>();
params.put("dep", DEP);
CustomPostRequest request = new CustomPostRequest(Request.Method.POST, Uris.URL_GET_DEP_CAT, params,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
List<PCatValues> valores = parsear_y_devolver_valores(jsonObject);
gestionar_entregas(valores);
//aqui quitar los dialogos
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
ApiController.getInstance().addToRequestQueue(request);
ApiController is my Aplication singleton class.
public class ApiController extends Application {
public static final String TAG = ApiController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static ApiController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
/*FacebookSdk.sdkInitialize(getApplicationContext());
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.example.android.facebookloginsample", // replace with your unique package name
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.e("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}*/
}
public static synchronized ApiController getInstance() {
return mInstance;
}
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);
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);
}
}
}
I use volley, and this is what I do. The code goes anywhere in your activity.
import com.android.volley.Response.Listener;
import static com.android.volley.Response.ErrorListener;
Listener<YOURDATACLASS> successListener = new Listener<YOURDATACLASS>() {
@Override
public void onResponse(YOURDATACLASS data) {
// Check to make sure that the activity hasn't been destroyed while the call was in flight.
if (! isFinishing()) {
//DO YOUR UI UPDATE, such as
TextView textview = (TextView) findViewById(R.id.yourtextview);
textview.setText("blah blah blah");
}
}
};
ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//DO SOMETHING ON FAILURE
}
YOURAPICALL(successListener, failurelistener);