Retrofit is one of the famous HTTP libraries used to parse the data from remote databases using APIs. This library can be used to fetch the data from API in the form of JSON and display the API data within our application.
Implementation
We will be creating a simple application in which we will be creating an image view for displaying the image. After that we are creating two text views for displaying the full name & email from API.
- Step 1: Create a new project with empty activity & Proceed.
- Step 2: Open the build.gradle file of your project and add Retrofit, Picasso & Gson libraries like this
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.jakewharton.retrofit:retrofit1-okhttp3-client:1.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
- Step 3: Add the internet permission in AndroidManifest.xml like this
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.retrofitexample">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.RetrofitExample"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
- Step 4: Now we will create a data model to parse JSON data like this
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class RetrofitModel {
@SerializedName("data")
@Expose
private Data data;
public Data getData() {
return data;
}
public class Data {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("email")
@Expose
private String email;
@SerializedName("first_name")
@Expose
private String firstName;
@SerializedName("last_name")
@Expose
private String lastName;
@SerializedName("avatar")
@Expose
private String avatar;
public Integer getId() {
return id;
}
public String getEmail() {
return email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getAvatar() {
return avatar;
}
}
}
- Step 5: Create the retrofit instance.
We need to create an instance using Retrofit. Builder class and configure it with a base URL to issue network requests to a rest API with Retrofit. Here BASE_URL is the basic URL of our API where we will make a call.
import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Api {
Retrofit retrofit = null;
private static final int connectTimeOut = 2, readTimeOut = 3, writeTimeOut = 120;
public Retrofit getClient(final String token_) {
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
OkHttpClient client = new OkHttpClient.Builder().
connectTimeout(connectTimeOut, TimeUnit.MINUTES)
//.cookieJar(new JavaNetCookieJar(cookieManager))
.readTimeout(readTimeOut,TimeUnit.MINUTES).addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
String token = "Bearer "+ token_;
String userAgent = System.getProperty("http.agent");
Request request = null;
if (token != null) {
request = original.newBuilder()
.header("User-Agent",userAgent)
.header("Content-Type","text/html")
.header("Accept", "application/json")
.header("X-Requested-With", "ANDROID")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
return chain.proceed(original);
}
})
.writeTimeout(writeTimeOut, TimeUnit.SECONDS)
.build();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("BASE URL")
.addConverterFactory(GsonConverterFactory.create())
.client(client);
retrofit=builder.build();
return retrofit;
}
- Step 6. Define the Endpoints.
The endpoints are defined inside of an interface using special retrofit annotations to encode details about the parameters and request method.
public interface ApiInterface2 {
@GET("users/2")
Call<RetrofitModel> viewUsers();
}
- Step 7. Final step.
Inside the onCreate() method of the MainActivity.java, we initialize an instance of the ApiInterface2 interface, the Imageview, and also the Textviews. Finally, we call the getUser() method.
public class MainActivity extends AppCompatActivity {
ImageView image;
LinearLayout text_layout;
TextView name,email;
ProgressBar progress_bar;
Call<RetrofitModel> call1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = findViewById(R.id.image);
email = findViewById(R.id.email);
text_layout = findViewById(R.id.text_layout);
name = findViewById(R.id.name);
progress_bar = findViewById(R.id.progress_bar);
getUser();
}
public void getUser() {
progress_bar.setVisibility(View.VISIBLE);
image.setVisibility(View.GONE);
email.setVisibility(View.GONE);
text_layout.setVisibility(View.GONE);
name.setVisibility(View.GONE);
// final SweetAlertDialog pDialog = Dialogs.showProgressDialog(mActivity, "Loading...");
ApiInterface2 apiInterface=(new Api().getClient("").create(ApiInterface2.class));
call1 = apiInterface.viewUsers();
call1.enqueue(new Callback<RetrofitModel>() {
@Override
public void onResponse(Call<RetrofitModel> call, Response<RetrofitModel> response) {
progress_bar.setVisibility(View.GONE);
if (response.code() == 200) {
image.setVisibility(View.VISIBLE);
email.setVisibility(View.VISIBLE);
text_layout.setVisibility(View.VISIBLE);
name.setVisibility(View.VISIBLE);
Picasso.with(MainActivity.this)
.load(response.body().getData().getAvatar())
// .resize(Integer.parseInt(context.getResources().getString(R.string.targetProductImageWidth1)),Integer.parseInt(context.getResources().getString(R.string.targetProductImageHeight)))
.placeholder(R.mipmap.ic_launcher)
.into(image);
name.setText("Name : "+response.body().getData().getFirstName()+" "+response.body().getData().getLastName());
email.setText("Email : "+response.body().getData().getEmail());
} else {
text_layout.setVisibility(View.VISIBLE);
name.setVisibility(View.VISIBLE);
name.setText("some error occurred");
}
}
@Override
public void onFailure(Call<RetrofitModel> call, Throwable t) {
if(progress_bar!=null)
progress_bar.setVisibility(View.GONE);
text_layout.setVisibility(View.VISIBLE);
name.setVisibility(View.VISIBLE);
name.setText("some error occurred");
Log.e("error", t.toString());
}
});
}
}
Below is the activity_main.xml file.
<RelativeLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:src="@mipmap/ic_launcher"
/>
<LinearLayout
android:id="@+id/text_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/image"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
<TextView
android:id="@+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Hello World!" />
</LinearLayout>
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal|center_vertical"
android:visibility="visible" />
</RelativeLayout>
Understanding
enqueue() asynchronously sends the request and notifies the app with a callback when API returns the response. Retrofit handles it on background thread to prevent the UI thread from getting blocked or interfered with
In order to use enqueue(), we have to implement two callback methods:
- onResponse()
- onFailure()
Fire up the app
Finally, you can run the app and see the output.
Leave a Reply