In this tutorial, we will build a login system using Retrofit, following the MVVM design pattern in Java. When the login button is clicked, a remote API call is made, and a login token is returned.
This tutorial was created based on a user request, and it's our top priority. Let's get started!
Watch the Video Tutorial
If you prefer a step-by-step walkthrough, watch the video tutorial below:
Step 1: Adding Internet Permissions
First, we need to add internet permissions in the Android Manifest file:
<uses-permission android:name="android.permission.INTERNET" />
Step 2: Adding Retrofit Dependencies
Next, add the following Retrofit dependencies to your build.gradle file:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
Step 3: Sync the Project
After adding the dependencies, sync the project to include them.
Step 4: Creating Retrofit Client
Now, create a new class named RetrofitClientInstance.java to manage the Retrofit client:
public class RetrofitClientInstance {
private static Retrofit retrofit;
private static final String BASE_URL = "https://api.example.com/";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Step 5: Creating Data Models
We need to create the LoginBody and LoginResponse model classes. The LoginBody class will hold the user’s email and password:
public class LoginBody {
@SerializedName("email")
private String email;
@SerializedName("password")
private String password;
public LoginBody(String email, String password) {
this.email = email;
this.password = password;
}
// Getters and Setters
}
Now, create the LoginResponse class that contains the response token:
public class LoginResponse {
@SerializedName("token")
private String token;
public String getToken() {
return token;
}
}
Step 6: Creating the Login API Service
Create an interface for the login service in ILoginService.java:
public interface ILoginService {
@POST("api/login")
Call<LoginResponse> login(@Body LoginBody loginBody);
}
Step 7: Creating the Repository
Now, let's move to the Repository. In the Repository class, create a method to handle the login request:
public class LoginRepository {
private ILoginService loginService;
public LoginRepository() {
loginService = RetrofitClientInstance.getRetrofitInstance().create(ILoginService.class);
}
public void login(LoginBody loginBody, ILoginResponseCallback callback) {
Call<LoginResponse> call = loginService.login(loginBody);
call.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (response.isSuccessful()) {
callback.onResponse(response.body());
} else {
callback.onFailure(new Throwable("Login failed"));
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
callback.onFailure(t);
}
});
}
}
Step 8: Creating ViewModel
In the LoginViewModel class, create a method to call the repository’s login method and observe the result:
public class LoginViewModel extends ViewModel {
private MutableLiveData<String> loginResult = new MutableLiveData<>();
public void login(String email, String password) {
LoginBody loginBody = new LoginBody(email, password);
repository.login(loginBody, new ILoginResponseCallback() {
@Override
public void onResponse(LoginResponse response) {
loginResult.setValue("Login Success");
}
@Override
public void onFailure(Throwable t) {
loginResult.setValue("Login Failed");
}
});
}
public LiveData<String> getLoginResult() {
return loginResult;
}
}
Step 9: Updating the View
Finally, create the login form in your activity layout with two EditTexts for the email and password, and a login button:
<EditText
android:id="@+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
<Button
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login" />
In the Activity, observe the login result and show the appropriate message to the user:
loginViewModel.getLoginResult().observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
}
});
That's it for this tutorial! If you have any questions or requests for future tutorials, feel free to leave a comment below.
No comments:
Post a Comment
Share your thoughts ...