Update UI thread after network request in Volley A

2019-03-18 20:48发布

问题:

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 suggest handle requests and responses respectively. I follow this pattern so that I don't write redundant code. I just pass in the dynamic query/url as parameter and using a switch case handle the response to each of the requests. But I am stuck with the below problem :

I have no way of updating my UI thread from where I call the RequestHandler class. What I have tried or already know so far :

  1. Make the UI elements(Textview, Listview) static and update them after the response comes.
  2. Pass in a context parameter and update the UI after the response is received.
  3. Write the request and response as inner classes within the Activity
  4. Get rid of Volley.

I was wondering, how you guys do it? Is there any pattern better than the Request/Response Handler pattern I follow? Any way of updating the UI thread following the same pattern?

Thanks in advance !

回答1:

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


回答2:

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

}

}