Android Tutorial on Retrofit Library, Fetching data from server is a most common functionality almost in every app, and for which there are several parameters like time taken for fetching data or uploading, connectivity, speed, security and many more.
In this blog we will be looking over a library which will help you fetch data from your api’s much more faster.
Android Tutorial on Retrofit Library
Retrofit Library works with your HTTP API in making it into a java interface making it much flexible and faster for you, which also helps in over all performance of the app.
Fetching data from server is a common task in apps which may be related for analytics, upload / download of images, databases etc.
In this tutorial on Retrofit library we can fetch data from an api and show it in a android recyclerview.
Dependency :
Add Retrofit, recyclerview, gson to your project
Try to add the latest version of dependency’s to your project to avoid abnormal crashes by the usage of deprecated codes.
implementation 'com.squareup.retrofit:retrofit:2.0.0-beta2' compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2' compile 'com.android.support:recyclerview-v7:26.1.0' compile 'com.google.code.gson:gson:2.2.4'
Lets design the row of the listview
listview_row
Add two textviews to the layout for displaying username and age.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/nameTxt" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="name" android:layout_weight="1" android:padding="10dp"/> <TextView android:id="@+id/ageTxt" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="age" android:layout_weight="1" android:padding="10dp"/> </LinearLayout>
and then
activity_main :
Add a recyclerview to the layout file
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="retrofit.android.com.retrofit.MainActivity"> <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/recyclerView" android:scrollbars="vertical"> </android.support.v7.widget.RecyclerView> </LinearLayout>
then create a api interface
ApiInterface
In post declare your parameter and also the model class file to parse the response.
public interface ApiInterface { @POST("YOUR PARAMETER HERE") Call<List<Contact>> getcontacts(); }
ApiClient
Declare your base url here.
public class ApiClient { public static final String BASE_URL = "YOUR URL HERE"; public static Retrofit retrofit = null; public static Retrofit getApiClient(){ if(retrofit==null){ retrofit = new Retrofit.Builder().baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } return retrofit; } }
Pojo model class for handling data in between api and adapter.For a faster way to generate model classes refer this link using which model class is generated based on the json array specified
Contact
public class Contact { private String name; private String age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
RecyclerAdapter
Recycler adapter is used to improve the app performance by reusing the views multiple times.
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{ private List<Contact> contacts; public RecyclerAdapter(List<Contact> contacts) { this.contacts = contacts; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_row,parent,false); return new MyViewHolder(view); } @Override public void onBindViewHolder(RecyclerAdapter.MyViewHolder holder, int position) { holder.Name.setText(contacts.get(position).getName()); holder.Age.setText(contacts.get(position).getAge()); } @Override public int getItemCount() { return contacts.size(); } public class MyViewHolder extends RecyclerView.ViewHolder{ TextView Name,Age; public MyViewHolder(View itemView) { super(itemView); Name = (TextView) itemView.findViewById(R.id.nameTxt); Age = (TextView) itemView.findViewById(R.id.ageTxt); } } }
MainActivity
Now we can fetch data using our api interface
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
call.enqueue(new Callback<List<Contact>>() { @Override public void onResponse(Response<List<Contact>> response, Retrofit retrofit) { contacts = response.body(); adapter = new RecyclerAdapter(contacts); recyclerView.setAdapter(adapter); } @Override public void onFailure(Throwable t) { } });
public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private RecyclerView.LayoutManager layoutManager; private RecyclerAdapter adapter; private List<Contact> contacts; private ApiInterface apiInterface; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); recyclerView.setHasFixedSize(true); apiInterface = ApiClient.getApiClient().create(ApiInterface.class); Call<List<Contact>> call = apiInterface.getcontacts(); call.enqueue(new Callback<List<Contact>>() { @Override public void onResponse(Response<List<Contact>> response, Retrofit retrofit) { contacts = response.body(); adapter = new RecyclerAdapter(contacts); recyclerView.setAdapter(adapter); } @Override public void onFailure(Throwable t) { } }); } }
Manifest
Declare internet permission
<uses-permission android:name="android.permission.INTERNET"/>
Output
The screen below depicts Android Tutorial on Retrofit Library usage
Any query’s on the tutorials do let us know in the comment section below or on instagram.