Retrofit is type safe REST client for Android. it make simple to call RESTfull services in Android.
Today we are going to learn Retrofit2 in this post.
Retrofit uses OkHttp for making Http requests. Retrofit easily convets JSON data inot POJO classes. For this conversion we need to pass Converters to Retrofit object.
Before start we should have to know about below points
Converters: Convert the JSON data into related POJO class.
Retrofit will support below converters
Interceptors: Interceptors are mechanism available in OkHttp to monitor, rewrite, and retry the calls for each request.
These are defined as below
Application Interceptors: To make application for Application Interceptors we need to add addInterceptor() to retrofit object.
Network Interceptors: TO make application for Network Interceptors we need to add addNetworkInterceptor() to retrofit object
To Implement code we need to follow below steps.
Add Related Dependencies
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:converter-gson:2.8.5'
implementation 'com.jakewharton:butterknife:10.2.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'
|
Here i have used ButterKnofe for ViewInjection
2) Create Retrofit Object
OkHttpClient client = new OkHttpClient.Builder().build();
|
If we want to add Interceptors
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
|
Here we created Retrofit object with our API base URL
3) Create Client Interface
Create an interface with required API methods.
Retrofit provides the list of annotations for each HTTP methods.
Example @GET,@POST,@PUT,@DELETE, @PATH...
Lets check our Client interface code
import retrofit2.Call; interface ServiceCall { @GET("api/classes.php")
|
Here we are using the POST method to get the Response data.
ResultData is my POJO class.
We can create POJO classes based on our response data
Just copy your response data and paste into JSON To POJO window, This will create repected POJO classes
We have different ways to send reauest params to API.
4) Use Retrofit Object and call API in Activity
ServiceCall call = retrofit.create(ServiceCall.class); if (response.isSuccessful()) { @Override |
In the Resposne GsonConverter automatically convert JSON resposne to Respected POJO classes.
Here the ResultData will be the POJO for the Classes Response.
Let see complete code.
ClassListActivity.java
public class ClassListActivity extends AppCompatActivity { @BindView(R.id.recyclerview) ClassAdapter classAdapter; private void callAPI() { Retrofit retrofit = new Retrofit.Builder() if (response.isSuccessful()) { classAdapter.addClasses(listCalsses); @Override @OnClick({R.id.recyclerview, R.id.txt_nodata}) |
activity_class_list.xml
|
ClassAdapter.java
public class ClassAdapter extends RecyclerView.Adapter { ListlistClass; @NonNull new ViewHolder(LayoutInflater.from(parent.getContext()).
inflate(R.layout.class_layout_item, parent, false)); @Override
(0,name.indexOf(" "))); @Override public void addClasses(Listclasses) } static
|
class_layout_item.xml
> android:id="@+id/img_class" android:id="@+id/txt_class" android:textColor="@color/white"
|
POJO Classes
public class ResultData { @SerializedName("data") public Boolean getError() { public void setError(Boolean error) { public String getMessage() { public void setMessage(String message) { public void setUser(List user) {
public class Classes implements ClassSubjects {
@SerializedName("id")
@Expose
private String id;
@SerializedName("name")
@Expose
private String name;
public boolean isSelected = false;
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 boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
|
ClassAdapter.java
public class ClassAdapter extends RecyclerView.Adapter { ListlistClass; public ClassAdapter(){ listClass=new ArrayList<>(); } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()). inflate(R.layout.class_layout_item, parent, false)); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { String name=listClass.get(position).getName(); holder.userName.setText(name); holder.txtClass.setText(name.substring (0,name.indexOf(" "))); } @Override public int getItemCount() { return listClass.size(); } public void addClasses(Listclasses) { listClass.clear(); for(Classes cls:classes) addClass(cls); } public void addClass(Classes cls) { listClass.add(cls); notifyItemInserted(listClass.size()-1); } static class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.img_class) ImageView imgClass; @BindView(R.id.txt_class) CustomTextview txtClass; @BindView(R.id.rel_pro) RelativeLayout relPro; @BindView(R.id.user_name) CustomTextview userName; public ViewHolder(@NonNull View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } } |
class_layout_item.xml
xmlns:app="https://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="@dimen/_2dp" app:cardCornerRadius="@dimen/_5dp" > android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="?attr/actionBarSize" android:layout_margin="@dimen/_5dp" > android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1"> android:id="@+id/rel_pro" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical"> android:id="@+id/img_class" android:layout_width="50dp" android:layout_height="50dp" android:layout_centerHorizontal="true" android:src="@drawable/circular_profile" /> android:id="@+id/txt_class" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:gravity="center_vertical|center_horizontal|center" android:text="U" android:textColor="@color/white" /> android:id="@+id/user_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_centerVertical="true" android:gravity="center_vertical" android:text="uername" android:textSize="22sp" android:textColor="@color/colorPrimary" android:textStyle="bold" android:layout_marginStart="@dimen/_16sp" android:layout_toEndOf="@+id/rel_pro" />
|
POJO Classes
public class ResultData { @SerializedName("error") @Expose private Boolean error; @SerializedName("message") @Expose private String message; @SerializedName("data") @Expose private List ClassSubjects; public Boolean getError() { return error; } public void setError(Boolean error) { this.error = error; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List getClasses() { return ClassSubjects; } public void setUser(List user) { this.ClassSubjects = user; } } public class Classes implements ClassSubjects { @SerializedName("id") @Expose private String id; @SerializedName("name") @Expose private String name; public boolean isSelected = false; 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 boolean isSelected() { return isSelected; } public void setSelected(boolean selected) { isSelected = selected; } } |
-->
Article Contributed By :
|
|
|
|
130 Views |