How to retrieve a list of cities based on a state ID using an API in Android?
How to retrieve a list of cities based on a state ID using an API in Android?
Title: Implementing Dynamic Spinners in Android using Retrofit
Introduction: Spinners are a common UI component used in Android applications to display a drop-down list of options. In some cases, the options for a spinner may depend on the selection made in another spinner. This dynamic behavior can be implemented using Retrofit, a popular library for making HTTP requests in Android applications. In this tutorial, we will explore how to implement dynamic spinners in Android using Retrofit.
Prerequisites: To follow along with this tutorial, you should have a basic understanding of Android development and have Android Studio installed on your machine.
Step 1: Setting up the Project:
- Open Android Studio and create a new project.
- Enter the project details and choose the desired settings.
- Once the project is created, navigate to the activity layout file (
activity_filters.xml) and add twoRelativeLayoutsections to hold the spinners and image views.
Step 2: Adding Dependencies:
- Open the project-level
build.gradlefile and add the Retrofit and OkHttp dependencies. - Sync the project to download the dependencies.
Step 3: Designing the Layout:
- Open the activity layout file (
activity_filters.xml) and add the necessary XML code for theRelativeLayout,Spinner, andImageViewcomponents. - Customize the layout as per your design requirements, including attributes such as layout width, height, margins, and background.
Step 4: Implementing the Retrofit API Calls:
- Create a new Java class called
ApiRequestto define the Retrofit API requests. - Add the necessary Retrofit annotations, such as
@GETand@Query, to specify the API endpoints and query parameters. - Create another Java class called
RetrofitRequestto configure the Retrofit instance and define the base URL. - Use the Retrofit instance to create an API service object in the
ApiRequestclass. - Implement the API methods in the
ApiRequestclass, such asgetStateList()andgetCityList(), to make the corresponding API calls.
Step 5: Implementing the Activity Logic:
- Open the
Filtersactivity class and initialize thestateSpinnerandcitySpinnervariables. - Create two
ArrayAdapterobjects,stateAdapterandcityAdapter, to populate the spinners with data. - In the
onCreate()method, set thecityAdapterwith a default "Select City" option and attach it to thecitySpinner. - Call the
getStateApi()method to fetch the state list from the API and populate thestateSpinner. - In the
getStateApi()method, make the Retrofit API call to retrieve the state list. - If the API response is successful, parse the response body and populate the
stateList. - Set the
stateAdapterwith thestateListand attach it to thestateSpinner. - Implement the
onResponse()andonFailure()callbacks to handle the API response and error cases. - Create a
getCityApi()method to fetch the city list based on the selected state. - In the
getCityApi()method, make the Retrofit API call to retrieve the city list. - If the API response is successful, parse the response body and populate the
cityList. - Set the
cityAdapterwith thecityListand attach it to thecitySpinner. - Implement the
onResponse()andonFailure()callbacks for the city
This is Xml Code ...
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginHorizontal="10dp"
>
<Spinner
android:id="@+id/stateSpinner"
android:layout_width="match_parent"
android:layout_height="50dp"
android:paddingHorizontal="20dp"
android:layout_marginHorizontal="10dp"
android:background="@drawable/input_bg_rounded"
>
</Spinner>
<ImageView
android:layout_marginRight="30dp"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:src="@drawable/down_arrow"
android:layout_alignParentRight="true"
>
</ImageView>
</RelativeLayout>
<RelativeLayout
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginHorizontal="10dp"
>
<Spinner
android:id="@+id/citySpinner"
android:layout_width="match_parent"
android:layout_height="50dp"
android:paddingHorizontal="20dp"
android:layout_marginHorizontal="10dp"
android:background="@drawable/input_bg_rounded"
>
</Spinner>
<ImageView
android:layout_marginRight="30dp"
android:layout_width="20dp"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:src="@drawable/down_arrow"
android:layout_alignParentRight="true"
>
</ImageView>
</RelativeLayout>
this is Class Code tnxx... package com.daizzyinfo.vidhikseva.activities;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.daizzyinfo.vidhikseva.R;
import com.daizzyinfo.vidhikseva.retrofit.ApiRequest;
import com.daizzyinfo.vidhikseva.retrofit.RetrofitRequest;
import com.daizzyinfo.vidhikseva.viewModel.city.CityResponse;
import com.daizzyinfo.vidhikseva.viewModel.state.StateResponse;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Filters extends AppCompatActivity {
Spinner stateSpinner, citySpinner;
// ArrayAdapter
ArrayAdapter<String> stateAdapter, cityAdapter;
List<String> stateList = new ArrayList<>();
List<String> cityList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filters);
stateSpinner = findViewById(R.id.stateSpinner);
citySpinner = findViewById(R.id.citySpinner);
// City API
cityList.add("Select City");
cityAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, cityList);
citySpinner.setAdapter(cityAdapter);
// State API
getStateApi();
}
public void getCityAPi(String state_id) {
cityList.clear();
cityList.add("Select City");
cityAdapter = new ArrayAdapter(this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,cityList);
citySpinner.setAdapter(cityAdapter);
ApiRequest apiRequest = RetrofitRequest.getRetrofit().create(ApiRequest.class);
CityJsonModel model = new CityJsonModel(state_id);
Call<CityResponse> call = apiRequest.getCitiesData(Constant.Token,model);
call.enqueue(new Callback<CityResponse>() {
@Override
public void onResponse(Call<CityResponse> call, Response<CityResponse> response) {
if (response.isSuccessful() && response.body() != null) {
if(response.code()==200){
for(int i = 0; i < response.body().getData().size(); i++) {
cityList.add(response.body().getData().get(i).getCityName()) ;
}
cityAdapter.notifyDataSetChanged();
}
}else if(response.code()==404)
{
Toast.makeText(Filters.this, "Not Found", Toast.LENGTH_SHORT).show();
}else if(response.code()==401)
{
Toast.makeText(Filters.this, "You Are Unauthorized", Toast.LENGTH_SHORT).show();
}else if(response.code()==500)
{
Toast.makeText(Filters.this, "Server Error", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(Filters.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<CityResponse> call, Throwable t) {
Toast.makeText(Filters.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
});
}
public void getStateApi() {
stateList.clear();
stateList.add("Select State");
stateAdapter = new ArrayAdapter(this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,stateList);
stateSpinner.setAdapter(stateAdapter);
ApiRequest apiRequest = RetrofitRequest.getRetrofit().create(ApiRequest.class);
Call<StateResponse> call = apiRequest.getState(Constant.Token);
call.enqueue(new Callback<StateResponse>() {
@Override
public void onResponse(Call<StateResponse> call, Response<StateResponse> response) {
if(response.code()==200){
for(int i = 0 ; i < response.body().getData().size() ; i++) {
stateList.add(response.body().getData().get(i).getStateName());
stateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position > 0)
{
String StateId = response.body().getData().get(position-1).getStateId().toString();
getCityAPi(StateId);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
swipeRefreshF.setRefreshing(false);
}
stateAdapter.notifyDataSetChanged();
}else if(response.code()==404)
{
Toast.makeText(Filters.this, "Not Found", Toast.LENGTH_SHORT).show();
}else if(response.code()==401)
{
Toast.makeText(Filters.this, "You Are Unauthorized", Toast.LENGTH_SHORT).show();
}else if(response.code()==500)
{
Toast.makeText(Filters.this, "Server Error", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(Filters.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<StateResponse> call, Throwable t) {
Toast.makeText(Filters.this, "Something went Wrong ", Toast.LENGTH_SHORT).show();
}
});
}
2nd Solutions
package com.daizzyinfo.vidhikseva.activities;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.daizzyinfo.vidhikseva.R;
import com.daizzyinfo.vidhikseva.retrofit.ApiRequest;
import com.daizzyinfo.vidhikseva.retrofit.RetrofitRequest;
import com.daizzyinfo.vidhikseva.viewModel.city.CityResponse;
import com.daizzyinfo.vidhikseva.viewModel.state.StateResponse;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Filters extends AppCompatActivity {
Spinner stateSpinner, citySpinner;
// ArrayAdapter
ArrayAdapter<String> stateAdapter, cityAdapter;
List<String> stateList = new ArrayList<>();
List<String> cityList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filters);
stateSpinner = findViewById(R.id.stateSpinner);
citySpinner = findViewById(R.id.citySpinner);
// City API
cityList.add("Select City");
cityAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, cityList);
citySpinner.setAdapter(cityAdapter);
// State API
getStateApi();
}
private void getStateApi() {
ApiRequest apiRequest = RetrofitRequest.getRetrofitInstance().create(ApiRequest.class);
Call<StateResponse> call = apiRequest.getStateList();
call.enqueue(new Callback<StateResponse>() {
@Override
public void onResponse(Call<StateResponse> call, Response<StateResponse> response) {
if (response.isSuccessful()) {
StateResponse stateResponse = response.body();
if (stateResponse != null) {
stateList.clear();
stateList.add("Select State");
stateList.addAll(stateResponse.getStateList());
stateAdapter = new ArrayAdapter<>(Filters.this, android.R.layout.simple_spinner_dropdown_item, stateList);
stateSpinner.setAdapter(stateAdapter);
}
} else {
Log.e("State API", "Response error: " + response.code());
}
}
@Override
public void onFailure(Call<StateResponse> call, Throwable t) {
Log.e("State API", "Request error: " + t.getMessage());
}
});
}
private void getCityApi(String stateCode) {
ApiRequest apiRequest = RetrofitRequest.getRetrofitInstance().create(ApiRequest.class);
Call<CityResponse> call = apiRequest.getCityList(stateCode);
call.enqueue(new Callback<CityResponse>() {
@Override
public void onResponse(Call<CityResponse> call, Response<CityResponse> response) {
if (response.isSuccessful()) {
CityResponse cityResponse = response.body();
if (cityResponse != null) {
cityList.clear();
cityList.add("Select City");
cityList.addAll(cityResponse.getCityList());
cityAdapter = new ArrayAdapter<>(Filters.this, android.R.layout.simple_spinner_dropdown_item, cityList);
citySpinner.setAdapter(cityAdapter);
}
} else {
Log.e("City API", "Response error: " + response.code());
}
}
@Override
public void onFailure(Call<CityResponse> call, Throwable t) {
Log.e("City API", "Request error: " + t.getMessage());
}
});
}
}
.jpeg)
Comments
Post a Comment