Tuesday 25 July 2023

How to call get parametrized api in android java in Repository design pattern. Explain with Example

To call a parameterized GET API in Android Java using the Repository design pattern, you can modify the ApiService and UserRepository interfaces to include the necessary parameters and use them in the API call. Let's assume we want to fetch user data by passing a user ID as a parameter to the API. Here's an example of how to achieve this:

  1. Create an updated version of the ApiService interface to include the parameterized GET API:

ApiService.java:

----------------------------------------------------------------------------------------------------------------------

import java.util.List;

import retrofit2.Call;

import retrofit2.http.GET;

import retrofit2.http.Path;


public interface ApiService {

    @GET("users")

    Call<List<User>> getUsers();


    @GET("users/{userId}")

    Call<User> getUserById(@Path("userId") int userId);

}

----------------------------------------------------------------------------------------------------------------------
  1. Modify the UserRepository interface to include the parameterized API method:

UserRepository.java:

----------------------------------------------------------------------------------------------------------------------

import java.util.List;

import retrofit2.Callback;


public interface UserRepository {

    void getUsers(Callback<List<User>> callback);


    void getUserById(int userId, Callback<User> callback);

}

----------------------------------------------------------------------------------------------------------------------

  1. Update the RemoteUserRepository to implement the new method:

RemoteUserRepository.java:

----------------------------------------------------------------------------------------------------------------------

import retrofit2.Call;

import retrofit2.Callback;

import retrofit2.Response;


public class RemoteUserRepository implements UserRepository {


    private ApiService apiService;


    public RemoteUserRepository(ApiService apiService) {

        this.apiService = apiService;

    }


    @Override

    public void getUsers(final Callback<List<User>> callback) {

        Call<List<User>> call = apiService.getUsers();

        call.enqueue(new Callback<List<User>>() {

            @Override

            public void onResponse(Call<List<User>> call, Response<List<User>> response) {

                if (response.isSuccessful()) {

                    List<User> users = response.body();

                    if (users != null) {

                        callback.onSuccess(users);

                    } else {

                        callback.onError("No users found");

                    }

                } else {

                    callback.onError("Failed to fetch users");

                }

            }


            @Override

            public void onFailure(Call<List<User>> call, Throwable t) {

                callback.onError(t.getMessage());

            }

        });

    }


    @Override

    public void getUserById(int userId, final Callback<User> callback) {

        Call<User> call = apiService.getUserById(userId);

        call.enqueue(new Callback<User>() {

            @Override

            public void onResponse(Call<User> call, Response<User> response) {

                if (response.isSuccessful()) {

                    User user = response.body();

                    if (user != null) {

                        callback.onSuccess(user);

                    } else {

                        callback.onError("User not found");

                    }

                } else {

                    callback.onError("Failed to fetch user");

                }

            }


            @Override

            public void onFailure(Call<User> call, Throwable t) {

                callback.onError(t.getMessage());

            }

        });

    }

}

----------------------------------------------------------------------------------------------------------------------

  1. Update the UserViewModel to use the new method for fetching a user by ID:

UserViewModel.java:

----------------------------------------------------------------------------------------------------------------------

import androidx.lifecycle.MutableLiveData;

import androidx.lifecycle.ViewModel;


public class UserViewModel extends ViewModel {


    private UserRepository userRepository;

    private MutableLiveData<List<User>> usersLiveData = new MutableLiveData<>();

    private MutableLiveData<User> userLiveData = new MutableLiveData<>();

    private MutableLiveData<String> errorLiveData = new MutableLiveData<>();


    public UserViewModel() {

        // Initialize the UserRepository (You can use Dependency Injection for this)

        userRepository = new RemoteUserRepository(ApiClient.getApiService());

        getUsers();

    }


    public void getUsers() {

        userRepository.getUsers(new Callback<List<User>>() {

            @Override

            public void onSuccess(List<User> users) {

                usersLiveData.setValue(users);

            }


            @Override

            public void onError(String errorMessage) {

                errorLiveData.setValue(errorMessage);

            }

        });

    }


    public void getUserById(int userId) {

        userRepository.getUserById(userId, new Callback<User>() {

            @Override

            public void onSuccess(User user) {

                userLiveData.setValue(user);

            }


            @Override

            public void onError(String errorMessage) {

                errorLiveData.setValue(errorMessage);

            }

        });

    }


    public MutableLiveData<List<User>> getUsersLiveData() {

        return usersLiveData;

    }


    public MutableLiveData<User> getUserLiveData() {

        return userLiveData;

    }


    public MutableLiveData<String> getErrorLiveData() {

        return errorLiveData;

    }

}

----------------------------------------------------------------------------------------------------------------------

Now, you can call the parameterized API by providing the user ID as an argument to the getUserById method in the UserViewModel. The ViewModel will handle the API call through the UserRepository and provide the response via LiveData, which can be observed by the UI components for updating the UI accordingly.

No comments:

Post a Comment