Skip to content

Instantly share code, notes, and snippets.

@xsahil03x
Created October 15, 2018 13:58
Show Gist options
  • Save xsahil03x/5e920331a084d0f75a9372e83606936d to your computer and use it in GitHub Desktop.
Save xsahil03x/5e920331a084d0f75a9372e83606936d to your computer and use it in GitHub Desktop.
Retrofit Boilerplate
public interface DummyApi {
@GET("posts")
Call<DemoPost> fetchDummyPosts();
@GET("comments")
Call<DemoComment> fetchDummyComments();
}
public class DummyApiBuilder {
private static final String BASE_URL = "https://jsonplaceholder.typicode.com/";
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;
}
}
public class DummyComment {
@SerializedName("postId")
@Expose
private Integer postId;
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("email")
@Expose
private String email;
@SerializedName("body")
@Expose
private String body;
public Integer getPostId() {
return postId;
}
public void setPostId(Integer postId) {
this.postId = postId;
}
public Integer getId() {
return id;
}
public void setId(Integer 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 getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
public class DummyPost {
@SerializedName("userId")
@Expose
private Integer userId;
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("title")
@Expose
private String title;
@SerializedName("body")
@Expose
private String body;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
Retrofit : implementation 'com.squareup.retrofit2:retrofit:2.4.0'
Gson : implementation 'com.google.code.gson:gson:2.4.0'
DummyApiBuilder.getClient().create(DummyApi.class)
.fetchDummyPosts()
.enqueue(new Callback<DummyPost>() {
@Override
public void onResponse(@NonNull Call<DummyPost> call, @NonNull Response<DummyPost> response) {
}
@Override
public void onFailure(Call<DummyPost> call, Throwable t) {
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment