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:

  1. Open Android Studio and create a new project.
  2. Enter the project details and choose the desired settings.
  3. Once the project is created, navigate to the activity layout file (activity_filters.xml) and add two RelativeLayout sections to hold the spinners and image views.

Step 2: Adding Dependencies:

  1. Open the project-level build.gradle file and add the Retrofit and OkHttp dependencies.
  2. Sync the project to download the dependencies.

Step 3: Designing the Layout:

  1. Open the activity layout file (activity_filters.xml) and add the necessary XML code for the RelativeLayout, Spinner, and ImageView components.
  2. 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:

  1. Create a new Java class called ApiRequest to define the Retrofit API requests.
  2. Add the necessary Retrofit annotations, such as @GET and @Query, to specify the API endpoints and query parameters.
  3. Create another Java class called RetrofitRequest to configure the Retrofit instance and define the base URL.
  4. Use the Retrofit instance to create an API service object in the ApiRequest class.
  5. Implement the API methods in the ApiRequest class, such as getStateList() and getCityList(), to make the corresponding API calls.

Step 5: Implementing the Activity Logic:

  1. Open the Filters activity class and initialize the stateSpinner and citySpinner variables.
  2. Create two ArrayAdapter objects, stateAdapter and cityAdapter, to populate the spinners with data.
  3. In the onCreate() method, set the cityAdapter with a default "Select City" option and attach it to the citySpinner.
  4. Call the getStateApi() method to fetch the state list from the API and populate the stateSpinner.
  5. In the getStateApi() method, make the Retrofit API call to retrieve the state list.
  6. If the API response is successful, parse the response body and populate the stateList.
  7. Set the stateAdapter with the stateList and attach it to the stateSpinner.
  8. Implement the onResponse() and onFailure() callbacks to handle the API response and error cases.
  9. Create a getCityApi() method to fetch the city list based on the selected state.
  10. In the getCityApi() method, make the Retrofit API call to retrieve the city list.
  11. If the API response is successful, parse the response body and populate the cityList.
  12. Set the cityAdapter with the cityList and attach it to the citySpinner.
  13. Implement the onResponse() and onFailure() 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());
}
});
}
}

 

Comments

Popular posts from this blog

API

How to get latitude longitude simply in Android using Address

Manifest