Getting Started with Retrofit
If you have ever made a HTTP network call using async tasks, then you know how much code we need to write for the network operation. We also have to take care of memory, caches, etc. So to make life easier, we have some libraries that can simplify our task. Retrofit is one of the most popularly used libraries for this job.
Retrofit is a REST Client for Android and Java by Square. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice. In Retrofit, you configure which converter is used for the data serialization. Typically for JSON, you use GSon, but you can add custom converters to process XML or other protocols. Retrofit uses the OkHttp library for HTTP requests.
To work with Retrofit, you need basically three classes.
Table of Contents
- Model class which is used to map the JSON data
- Interfaces which defines the possible HTTP operations
- Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL end point for the HTTP operation.
The API
https://jsonplaceholder.typicode.com/posts
JSON response
[ { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }, { "userId": 1, "id": 3, "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut", "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut" }, . . .
Create an Android Project Let’s get our hands dirty and create an Android Studio project. I've created mine and named it RetrofitLearn.
Add Internet Permission
<uses-permission android:name="android.permission.INTERNET"/>
Add this line of code to your manifest file above the application tag.
Add gradle dependencies
Adding libraries are very easy. You just need to add the following two lines inside the dependencies block of your app level build.gradle file.
Retrofit automatically serializes the JSON response using a POJO (Plain Old Java Object) which must be defined in advance for the JSON structure. To serialize JSON we need a converter to convert it into Gson first. That's the reason we added (implementation 'com.squareup.retrofit2:converter-gson:2.2.0').
The Model ClassTo get this title, we have to name our String as title (case sensitive) in the model class.
If you put the annotation @SerializedName (“attribute title”) with the JSON attribute name just above every variable you are defining, you can name your variables anything. But, you have to put the correct attribute name inside SerializedName (“title”).
Note: the value title inside the SerializedName ("title") is the same as the value "title" in the JSON response from the API.
Creating the API InterfaceTo make an API call using Retrofit, we need a Java interface where we define all of the URLs with the HTTP request type and parameters. In this example, we need to perform an HTTP GET with no extra parameters. Let's create a Java interface inside and name it PostApi.java
Displaying the Posts in a ListView
In the activity_main.xml of your project, create a ListView.
Fetching the JSON Data
Inside MainActivity.java, write the following code:
public class MainActivity extends AppCompatActivity { ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); listView = findViewById(R.id.postListView); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); getPosts(); } private void getPosts(){ //Creating a retrofit obkect Retrofit retrofit = new Retrofit.Builder() .baseUrl(PostApi.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); //creating the postApi interface PostApi postApi = retrofit.create(PostApi.class); //making the call object Call<List<Post>> call = postApi.getPosts(); call.enqueue(new Callback<List<Post>>() { @Override public void onResponse(@NonNull Call<List<Post>> call, @NonNull Response<List<Post>> response) { List<Post> postList = response.body(); //Creating a String array for the Listview String[] posts = new String[postList.size()]; //looping through all the posts for (int i = 0; i < postList.size(); i++){ posts[i] = postList.get(i).getTitle(); } //displaying the string array into listview listView.setAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, posts)); } @Override public void onFailure(Call<List<Post>> call, Throwable t) { Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }
}
Now you can run and test the app on an emulator or on a real device.