Skip to main content

Retrofit Demo

1 ) Main Activity

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @Override    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
        Call<ResponseOfAPI> call  = apiService.signUpData();
        call.enqueue(new Callback<ResponseOfAPI>() {
            @Override            
            public void onResponse(Call<ResponseOfAPI> call, Response<ResponseOfAPI> response) {
                //True Response                
                //Response code : 200               
                 List<Contact> contacts = response.body().getContacts();
                //Create adapter                
                //Supply this list into your adapter
                Log.d(TAG, "onResponse: No. of Contacts : " + contacts.size());
            }

            @Override            
            public void onFailure(Call<ResponseOfAPI> call, Throwable t) {
            //Dalse response           
            //Except 200            
            //Show error message
            }
        });
    }
}

2 ) API Client

public class ApiClient {
    public static final String BASE_URL = "http://api.androidhive.info/";
    private static Retrofit retrofit = null;


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


3 ) API Interface
public interface ApiInterface {
    @GET("contacts/")
    Call<ResponseOfAPI> getData();

    @GET("signup/")
    Call<ResponseOfAPI> signUpData();
}


4 ) Model Class
public class Contact {
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("address")
    @Expose
    private String address;
    @SerializedName("gender")
    @Expose
    private String gender;
    @SerializedName("phone")
    @Expose
    private Phone phone;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Phone getPhone() {
        return phone;
    }

    public void setPhone(Phone phone) {
        this.phone = phone;
    }
}


public class Phone {
    @SerializedName("mobile")
    @Expose
    private String mobile;
    @SerializedName("home")
    @Expose
    private String home;
    @SerializedName("office")
    @Expose
    private String office;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getHome() {
        return home;
    }

    public void setHome(String home) {
        this.home = home;
    }

    public String getOffice() {
        return office;
    }

    public void setOffice(String office) {
        this.office = office;
    }

}


5 ) Response API
public class ResponseOfAPI {
    @SerializedName("contacts")
    @Expose
    private List<Contact> contacts = null;

    public List<Contact> getContacts() {
        return contacts;
    }

    public void setContacts(List<Contact> contacts) {
        this.contacts = contacts;
    }
}




Notes : 

1 ) Require Graddle

compile 'com.android.support:appcompat-v7:25.2.0'compile 'com.squareup.retrofit2:retrofit:2.2.0'compile 'com.google.code.gson:gson:2.6.2'compile 'com.squareup.retrofit2:converter-gson:2.0.2'

Comments

Popular posts from this blog

Post data with retrofit

1 ) Retrofit Client Class public class RetrofitClient { private static final String AUTH = "Basic " + Base64. encodeToString (( "belalkhan:123456" ).getBytes(), Base64. NO_WRAP ); private static final String BASE_URL = "http://simplifiedlabs.xyz/MyApi/public/" ; private static RetrofitClient mInstance ; private Retrofit retrofit ; private RetrofitClient() { OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor( new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder() .addHeader( "Authorization" , AUTH ) .meth...

Android MVVM (Model View ViewModel) Design Pattern

DataBinding Pdf Link:-   https://drive.google.com/open?id=1uL0xK9EktcEWOke5vqUqp-rgqpA1ARR3 DataBinding References : -  https://www.youtube.com/watch?v=v4XO_y3RErI Steps for applying MVVM design pattern to Android Project  1 ) Applying the changes in build.gradle (App Level) file      android {     compileSdkVersion 27     defaultConfig {         applicationId "com.credencys.databindingwithrecyclerview"         minSdkVersion 15         targetSdkVersion 27         versionCode 1         versionName "1.0"         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"     }     buildTypes {         release {             minifyEnabled false             proguardFiles ge...

Complex Retrofit Class With Database

URL:-  http://www.mocky.io/v2/ 5b936d6f33000011002061d3 1 )   Create   RetrofitClient(Base URL Class) import retrofit2.GsonConverterFactory; import retrofit2.Retrofit; public class RetrofitClient { //http://www.mocky.io/v2/5b936d6f33000011002061d3 public static final String API_BASE_URL = "http://www.mocky.io/v2/" ; public static Retrofit retrofit = null ; public static Retrofit getApiClient() { if ( retrofit == null ) { retrofit = new Retrofit.Builder().baseUrl( API_BASE_URL ).addConverterFactory(GsonConverterFactory . create ()).build(); } return retrofit ; } } 2 ) Create Retrofit ApiInterface Class(End URL Class) import com.example.discusit.complexretrofitdemo.model.Data; import retrofit2.Call; import retrofit2.http. GET ; public interface ApiInterface { @GET ( "5b936d6f33000011002061d3" ) Call<Data> getData(); } 3 ) Create Require Model Clas...