Tuesday, 14 November 2017

How to use Retrofit Api in Android

1) First of all to add this dependencies in your app/build.gradle file 
 
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2' 
compile 'com.squareup.okhttp3:okhttp:3.4.1' 
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
 
2) then make one java class name Apiclient to declare api base link for getting data 
and this link is demo link so paste your link here 

public class ApiClient {
    public static final String BASE_URL = "http://domainname.com/folder";

    private static Retrofit retrofit = null;


    public static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor)
                                                    .build();

        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

3) To make one interface to declare the api name and param list and to use this link 
jsonschema2pojo.org for making pojo class of your response  
 
 
public interface APIInterface {

    //For Login    @GET("login")
    Call<GetSetMethod> getLoginResponse(@Query("username") String username,  
@Query("password") String password);

} 

4) Use all method and class in your main class where you want to get response for 
display.here is demo class for your reference 
 private void loginProcessWithRetrofit(final String username, String password) {
    // Showing progress dialog    pDialog = new ProgressDialog(LoginActivity.this);
    pDialog.setMessage("Please wait...");
    pDialog.setCancelable(false);
    pDialog.show();

    APIInterface apiService =
            ApiClient.getClient().create(APIInterface.class);

    Call<GetSetMethod> call = apiService.getLoginResponse(username, password);
    call.enqueue(new Callback<GetSetMethod>() {
        @Override        public void onResponse(Call<GetSetMethod> call, 
            Response<GetSetMethod> response) {
            Log.e("List size", ""+response.raw().request().url());
            String str_success = response.body().getSuccess();
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            if (str_success.equals("1")) {
                //Get Login Response 
                ResponseData responseData = response.body().getResponseData();
                String user_id = responseData.getId();
                String auth_key = responseData.getAuthkey();
                String app_type = responseData.getApp();
                        

                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.open_next,R.anim.close_next);
                finish();
            } else {
                Toast.makeText(getApplicationContext(), 
              "Username or Password does not Matched", Toast.LENGTH_SHORT).show();
            }
        }

        @Override 
            public void onFailure(Call<GetSetMethod> call, Throwable t) {
            // Log error here since request failed 
               if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            Toast.makeText(getApplicationContext(), "Login Failed"
          Toast.LENGTH_SHORT).show();
        }
    });
}