Android: get result from callback (networking KOUSH ION)

后端 未结 3 885
旧巷少年郎
旧巷少年郎 2021-01-04 21:28

For my app I need to contact our API from our server which returns some JSON.

While downloading the JSON, it should display a progressbar.

I figured I should

3条回答
  •  长情又很酷
    2021-01-04 21:38

    In my opinion the cleanest solution is to create a service that handles the dirty download logic and returns a future of your custom response class, that contains the success info and the json object.

    // in e.g JsonResponse.java
    public class JsonResponse() {
        public boolean ok;
        public JsonObject json;
    }
    
    // in Service.java
    public Future getId(final String id) {
        final SimpleFuture jsonFuture = new SimpleFuture<>();
    
        String url = IPAddress.PRODUCTION + Variables.get_id + id;
        Ion.with(context)
        .load("GET", url)
        .asJsonObject()
        .withResponse()
        .setCallback(new FutureCallback>() {
            @Override
            public void onCompleted(Exception e, Response response) {
                JsonResponse jsonResponse = new JsonResponse();
                if (response != null) {
                    if (response.getHeaders().code() != 200) {
                        jsonResponse.ok = false;
                    } else {
                        jsonResponse.ok = true;
                        jsonResponse.json = response.getResult();   
                    }
                }
                jsonFuture.setComplete(jsonResponse);
            }
        });
    
        return jsonFuture;
    }
    
    
    // in Activity.java
    private void loadUser(String userId) {    
        mLoadingSpinner.setVisibility(View.VISIBLE);
    
        service.getId(userId)
        .setCallback(new FutureCallback() {
    
            // onCompleted is executed on ui thread
            @Override
            public void onCompleted(Exception e, JsonResponse jsonResponse) {
                mLoadingSpinner.setVisibility(View.GONE);
                if (jsonResponse.ok) {
                    // Show intent using info from jsonResponse.json
                } else {
                    // Show error toast
                }
            }
        });
    }
    

提交回复
热议问题