Retrofit dependencies and code how to use in android

Retrofit
Dependencies  set in gradle:
compile 'com.squareup.retrofit:retrofit:1.9.0'compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
compile 'com.squareup.okhttp:okhttp:2.0.0'

Api Handler Class::
public class ApiHandler {
    private static final String BASE_URL = Constants.BASE_URL;
    private static final long HTTP_TIMEOUT = TimeUnit.SECONDS.toMillis(600);
    private static WebServices apiService;
    public static WebServices getApiService() {
        if (apiService == null) {
            OkHttpClient okHttpClient = new OkHttpClient();
            okHttpClient.setConnectTimeout(HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
            okHttpClient.setWriteTimeout(HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
            okHttpClient.setReadTimeout(HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .setEndpoint(BASE_URL)
                    .setClient(new OkClient(okHttpClient))
                    .setConverter(new GsonConverter(new Gson()))
                    .build();
            apiService = restAdapter.create(WebServices.class);
            return apiService;
        } else {
            return apiService;
        }
    }
}



Interface Required for Services::
public interface CallServices {
1.for simple get method
    @GET("/url/url")
    void name(Callback callback);

2.for post with parameter::
   @FormUrlEncoded   @POST("/url/url")
   void name(@FieldMap Map map, Callback callback);

3.for post with image upload::
@Multipart@POST("/url/url")
void name(@PartMap Map map, @Part("parameter_name") TypedFile typedFile, Callback callback);

4.for post with [ ]MultipartTypedOutput::
@POST("/url/url")
public void name(@Body MultipartTypedOutput attachments, Callback callback);
}


Call api in class:: 

1.for simple get.
private void callApi() {
    UIUtil.showProgressDialog(MainActivity.this);
    ApiHandler.getApiService().categoryMainAPI(new Callback() {
        @Override        public void success(ResponseCat responseCat, Response response) {
            UIUtil.hideDialog();
            if (responseCat == null) {
                Toast.makeText(MainActivity.this, "Something went wrong. Try again in some time", Toast.LENGTH_SHORT).show();
            }

            if (responseCat.getResponseData() == null) {
                Toast.makeText(MainActivity.this, "Something went wrong. Try again in some time", Toast.LENGTH_SHORT).show();
            }

            if (responseCat.getMessage() == null) {
                Toast.makeText(MainActivity.this, "Something went wrong. Try again in some time", Toast.LENGTH_SHORT).show();
            }

            if (!responseCat.getStatus().equals("1")) {
                Toast.makeText(MainActivity.this, "Something went wrong. Try again in some time", Toast.LENGTH_SHORT).show();
            }

           if (addResponseDetail.getStatus().equals("1")) {
                 Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
            }
        }
     }


        @Override        public void failure(RetrofitError error) {
            error.printStackTrace();
            error.getMessage();
        }
    });
}


2.for post with parameter::

private void callAPI() {
    UIUtil.showProgressDialog(Classname.this);
    ApiHandler.getApiService().Revieworderstepone(getFieldMap(), new Callback() {
        public void success(final ResponseClassName responsename, Response response) {
            UIUtil.hideDialog();
            if (responsename.equals(null)) {
               UIUtil.showCustomSimpleDialog(Classname.this, new CustomSimpleMessageDialog.SimpleDialogOnClickListener() {
                    @Override                    public void onOkayButtonClick() {
                        if (UIUtil.customSimpleMessageDialog != null) {
                            UIUtil.customSimpleMessageDialog.dismiss();
                        }
                    }

                }, Constants.DIALOG_INFO_TITLE, UIUtil.getTrimmedStringFromAPI("Server Error"), false);
                return;
            }

            if (responsename!= null) {
                if (responsename.getStatus().equals("1")) {
                }
            }

            if (responsename.getStatus().equals("0")) {
                UIUtil.showCustomSimpleDialog(Classname.this, new CustomSimpleMessageDialog.SimpleDialogOnClickListener() {
                    @Override                    public void onOkayButtonClick() {
                        if (UIUtil.customSimpleMessageDialog != null) {
                            UIUtil.customSimpleMessageDialog.dismiss();
                        }
                    }

                }, Constants.DIALOG_INFO_TITLE, UIUtil.getTrimmedStringFromAPI(responsename.getMessage()), false);
            }
        }

        @Override        public void failure(RetrofitError error) {
            error.printStackTrace();
            error.getMessage();
            UIUtil.showCustomSimpleDialog(Classname.this, new CustomSimpleMessageDialog.SimpleDialogOnClickListener() {
                @Override                public void onOkayButtonClick() {
                    if (UIUtil.customSimpleMessageDialog != null) {
                        UIUtil.customSimpleMessageDialog.dismiss();
                    }
                }

            }, Constants.DIALOG_INFO_TITLE, UIUtil.getTrimmedStringFromAPI("Server Error"), false);
        }
    });
}


private Map getFieldMap() {
    Map map = new HashMap<>();
    map.put("param_name", value);
}

3.for post with image upload::
TypedFile typedFile= new TypedFile("image/*", new File(imagePath));
ApiHandler.getApiService().EditProfile(getFieldMap(), typedFile, new Callback() {
            public void success(final ResponseClassName response, Response response) {
}


4.for post with [ ]MultipartTypedOutput::
ApiHandler.getApiService().name(getFieldMap(), new Callback() {
    @Override    public void success(ResponseClassName res, Response response) {
}
}


private MultipartTypedOutput getaddrecipi() {
MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
// multipartTypedOutput.addPart("user_id", new TypedString(text));multipartTypedOutput.addPart("user_id", new TypedString(session.getKeyUserId()));
///pass arralist
//public static ArrayList arrlits_name = new ArrayList<>();

JSONArray jsoIngradiantarray = new JSONArray();
for (int i = 0; i < Constants.INGREDIENT_LIST.size(); i++) {
    JSONObject obj = new JSONObject();
    try {
        obj.put("name", Constants.arrlits_name.get(i).getItem());
        jsoIngradiantarray.put(obj);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

No comments:

Powered by Blogger.