Many apps ask users to add the address in their apps. To make this task easy for the users they firstly prompt the user to add Pincode and from that Pincode, they fetch the data such as city and state name. So the user's task is reduced to add city and state names while entering the address. Along with many apps so, many websites use this functionality that they first prompts the user to add pin code and after adding Pincode the city and state fields are entered automatically. So in this article, we will take a look at How we can incorporate that feature and get the city and state name from any Pincode of India. The Pincode is also referred to as postal code which is used to get the details of the nearby post office. These codes are generally used to get the details of the post office such as name, city, state, and many other details.
What we are going to build in this article?
We will be building a simple application in which we will be entering a pin code and after clicking on a button we will get to see the details such as city name, state, and country. The Pincode is provided by Post Offices and postal services. Indian post is one of the most popular post service operators in India. So in this project, we will be using an API which is provided by Indian Post which will give us details such as city, state, and country name.
Step by Step Implementation
Step 1: Create a new project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Add dependency for api calls
Below is the dependency for Volley which we will be using to get the data from API of Indian Post.
implementation 'com.android.volley:volley:1.2.1'
After adding this dependency sync your project and now move toward the XML part.
Step 3: Add permissions in manifests
Navigate to the app > AndroidManifest.xml file and add the permission for internet. Remember to set usesCleartextTraffic="true" to enable our application to make api calls to http servers since http servers are disabled by default from Android 9+.
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...
</application>Step 4: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="64dp"
android:hint="Enter pin code"
android:inputType="number"
android:maxLines="1"
android:singleLine="true" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="32dp"
android:layout_gravity="center_horizontal"
android:text="Get city and state"
android:textAllCaps="false" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="details goes here..."
android:textAlignment="center"
android:textSize="20sp" />
</LinearLayout>
Design UI:

Step 5: Working with the MainActivity file
Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail.
MainActivity File:
package org.geeksforgeeks.demo;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private EditText editText;
private TextView textView;
private RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
Button button = findViewById(R.id.button);
textView = findViewById(R.id.textView);
// Initialize request queue for Volley
requestQueue = Volley.newRequestQueue(this);
button.setOnClickListener(v -> {
// Get user input
String pinCode = editText.getText().toString().trim();
// Check whether user input is empty
if (TextUtils.isEmpty(pinCode)) {
Toast.makeText(this, "Please enter a valid pin code", Toast.LENGTH_SHORT).show();
} else {
getDataFromPinCode(pinCode);
}
});
}
@SuppressLint("SetTextI18n")
private void getDataFromPinCode(String pinCode) {
// Clear cache before request
requestQueue.getCache().clear();
// URL to fetch data
String url = "http://www.postalpincode.in/api/pincode/" + pinCode;
// Create object request using Volley
JsonObjectRequest objectRequest = new JsonObjectRequest(
Request.Method.GET, url, null,
response -> {
try {
// Check whether pin code is valid
if (!response.has("Status") || !"Success".equals(response.getString("Status"))) {
textView.setText("Pin code is not valid.");
return;
}
// Get data from response
JSONArray postOfficeArray = response.getJSONArray("PostOffice");
if (postOfficeArray.length() == 0) {
textView.setText("No details available for this pin code.");
return;
}
// Extract data from response
JSONObject obj = postOfficeArray.getJSONObject(0);
String district = obj.getString("District");
String state = obj.getString("State");
String country = obj.getString("Country");
// Display data in text view
textView.setText("Details of pin code:\n" +
"District: " + district + "\n" +
"State: " + state + "\n" +
"Country: " + country);
} catch (JSONException e) {
// Handle JSON exception
e.printStackTrace();
textView.setText("Error parsing data.");
}
},
error -> {
// Handle Volley error
textView.setText("Error fetching data: \n" + error.getMessage());
}
);
// Add object request to request queue
requestQueue.add(objectRequest);
}
}
package org.geeksforgeeks.demo
import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.*
import com.android.volley.toolbox.*
import org.json.JSONException
class MainActivity : AppCompatActivity() {
private lateinit var editText: EditText
private lateinit var button: Button
private lateinit var textView: TextView
private lateinit var requestQueue: RequestQueue
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
editText = findViewById(R.id.editText)
button = findViewById(R.id.button)
textView = findViewById(R.id.textView)
// Initialize request queue for volley
requestQueue = Volley.newRequestQueue(this)
button.setOnClickListener {
// get user input
val pinCode = editText.text.toString().trim()
// check whether user input is empty
if (TextUtils.isEmpty(pinCode)) {
Toast.makeText(this, "Please enter a valid pin code", Toast.LENGTH_SHORT).show()
} else {
getDataFromPinCode(pinCode)
}
}
}
@SuppressLint("SetTextI18n")
private fun getDataFromPinCode(pinCode: String) {
// Clear cache before request
requestQueue.cache.clear()
// url to fetch data
val url = "http://www.postalpincode.in/api/pincode/$pinCode"
// create object request using volley
val objectRequest = JsonObjectRequest(
Request.Method.GET, url, null,
Response.Listener { response ->
try {
// check whether pin code is valid
if (!response.has("Status") || response.getString("Status") != "Success") {
textView.text = "Pin code is not valid."
return@Listener
}
// get data from response
val postOfficeArray = response.getJSONArray("PostOffice")
if (postOfficeArray.length() == 0) {
textView.text = "No details available for this pin code."
return@Listener
}
// extract data from response
val obj = postOfficeArray.getJSONObject(0)
val district = obj.getString("District")
val state = obj.getString("State")
val country = obj.getString("Country")
// display data in text view
textView.text = """
Details of pin code:
District: $district
State: $state
Country: $country
""".trimIndent()
} catch (e: JSONException) {
// handle json exception
e.printStackTrace()
textView.text = "Error parsing data."
}
}
) { error ->
// handle volley error
textView.text = "Error fetching data: \n${error.message}"
}
// add object request to request queue
requestQueue.add(objectRequest)
}
}
Refer to the following github repo to get the entire code: Android get city name from pincode