Retrofit Android Example

 Why do we use retrofit in Android? :

Retrofit is used to perform the following tasks: It manages the process of receiving, sending, and creating HTTP requests and responses. It alternates IP addresses if there is a connection to a web service failure. It caches responses to avoid sending duplicate requests :
Step-1: Make Retrofit Client.Java Class  For Networking  :

public class RetrofitClient {

private static final String BASE_URL ="https://pass website Domain Name/api/";
private static RetrofitClient mInstance;
private Retrofit retrofit;


private RetrofitClient(){

OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.callTimeout(2, TimeUnit.MINUTES)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS);

retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
}

public static synchronized RetrofitClient getInstance(){
if(mInstance == null){
mInstance = new RetrofitClient();
}
return mInstance;
}

public Api getApi(){
return retrofit.create(Api.class);
}


}
Step-2 Make  Api interface Store Api;
public interface Api {

@FormUrlEncoded
@POST("pass after api word here")
Call<GetAllBlogResponseModel> userNo(
//Pass all faild here
@Field("Mobile") String Mobile
); }
Main Activity.java class code :
 if (Validator.getInstance().isNetworkAvailable(currentActivity)) {
String pageno = String.valueOf(currentPage);

String pagesize = String.valueOf(PageSize);


Call<GetAllBlogResponseModel> call = RetrofitClient.getInstance()
.getApi().getuserNo(Pass all value of given Fiald here);

call.enqueue(new Callback<GetAllBlogResponseModel>() {
@Override
public void onResponse(Call<GetAllBlogResponseModel> call, Response<GetAllBlogResponseModel> response) {
if (response.isSuccessful()) {
swipeRefresh.setRefreshing(false);
GetAllBlogResponseModel responseModel = response.body();
String status = String.valueOf(responseModel.getStatus());
if (status.equals("1")) {




} else if (status.equals("0")) {
swipeRefresh.setRefreshing(false);
Toast.makeText(currentActivity, Log.e("TAG", responseModel.toString()), Toast.LENGTH_SHORT).show();
}

} else if (response.code() == 401) {
swipeRefresh.setRefreshing(false);
Toast.makeText(currentActivity, "Your Session has been Expiered,Please Login Again..", Toast.LENGTH_SHORT).show();
} else if (response.code() == 500) {
swipeRefresh.setRefreshing(false);
Toast.makeText(currentActivity, "Server Error", Toast.LENGTH_SHORT).show();
} else {
swipeRefresh.setRefreshing(false);
Toast.makeText(currentActivity, "Failed to Retrieve Items..", Toast.LENGTH_SHORT).show();
}
}

@Override
public void onFailure(Call<GetAllBlogResponseModel> call, Throwable t) {
swipeRefresh.setRefreshing(false);
if (t instanceof SocketTimeoutException) {
cancelProgressDialog();
try {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(currentActivity);
dialogBuilder.setMessage("oops! it seems there is a slow network connection issue.");

dialogBuilder.setPositiveButton("OK", (dialog, which) -> {


dialog.dismiss();
}
);

dialogBuilder.setIcon(R.drawable.aajjo_logo_final);
dialogBuilder.setTitle("Network Connection.");

AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}

} else {
cancelProgressDialog();
Toast.makeText(currentActivity, t.toString(), Toast.LENGTH_SHORT).show();

}
}
});
} else {
//show alert Dialog Box
}
}
Retrofit dependencies :
implementation 'com.squareup.retrofit2:retrofit:2.6.2'  //for upload multiple image
implementation 'com.squareup.retrofit2:converter-gson:2.6.2' //for upload multiple image

Rajeshbhatt12

My name is Rajesh Bhatt. I am working as a senior android developer . I have created this blog for kotlin ,java and Android Development interview questions etc..

Previous Post Next Post