Open In App

How to Get City and State Name from Pincode in Android?

Last Updated : 03 Jan, 2023
Like Article

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 prompt 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. Below is the GIF image in which we will get to know what we are going to build in this article. 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. Note that select Java as the programming language.

Step 2: Add the below dependency in your build.gradle file

Below is the dependency for Volley which we will be using to get the data from API of Indian Post. 

implementation ‘’

After adding this dependency sync your project and now move toward the XML part. 

Step 3: 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.


<?xml version="1.0" encoding="utf-8"?>
    <!--heading text view-->
        android:text="Pin code validator"
        android:textSize="30sp" />
    <!-- edit text for entering our pin code
         we are specifying input type as number-->
        android:hint="Enter pin code"
        android:singleLine="true" />
    <!--button to get the data from pin code-->
        android:text="Get city and state"
        android:textAllCaps="false" />
    <!--text view to display the data
        received from pin code-->
        android:textSize="20sp" />

Step 4: Working with the file

Go to the file and refer to the following code. Below is the code for the file. Comments are added inside the code to understand the code in more detail.


import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
    // creating variables for edit text,
    // button and our text views.
    private EditText pinCodeEdt;
    private Button getDataBtn;
    private TextView pinCodeDetailsTV;
    // creating a variable for our string.
    String pinCode;
    // creating a variable for request queue.
    private RequestQueue mRequestQueue;
    protected void onCreate(Bundle savedInstanceState) {
        // initializing our variables.
        pinCodeEdt = findViewById(;
        getDataBtn = findViewById(;
        pinCodeDetailsTV = findViewById(;
        // initializing our request que variable with request
        // queue and passing our context to it.
        mRequestQueue = Volley.newRequestQueue(MainActivity.this);
        // initializing on click listener for our button.
        getDataBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // getting string  from EditText.
                pinCode = pinCodeEdt.getText().toString();
                // validating if the text is empty or not.
                if (TextUtils.isEmpty(pinCode)) {
                    // displaying a toast message if the
                    // text field is empty
                    Toast.makeText(MainActivity.this, "Please enter valid pin code", Toast.LENGTH_SHORT).show();
                } else {
                    // calling a method to display
                    // our pincode details.
    private void getDataFromPinCode(String pinCode) {
        // clearing our cache of request queue.
        // below is the url from where we will be getting
        // our response in the json format.
        String url = "" + pinCode;
        // below line is use to initialize our request queue.
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        // in below line we are creating a
        // object request using volley.
        JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            public void onResponse(JSONObject response) {
                // inside this method we will get two methods
                // such as on response method
                // inside on response method we are extracting
                // data from the json format.
                try {
                    // we are getting data of post office
                    // in the form of JSON file.
                    JSONArray postOfficeArray = response.getJSONArray("PostOffice");
                    if (response.getString("Status").equals("Error")) {
                        // validating if the response status is success or failure.
                        // in this method the response status is having error and
                        // we are setting text to TextView as invalid pincode.
                        pinCodeDetailsTV.setText("Pin code is not valid.");
                    } else {
                        // if the status is success we are calling this method
                        // in which we are getting data from post office object
                        // here we are calling first object of our json array.
                        JSONObject obj = postOfficeArray.getJSONObject(0);
                        // inside our json array we are getting district name,
                        // state and country from our data.
                        String district = obj.getString("District");
                        String state = obj.getString("State");
                        String country = obj.getString("Country");
                        // after getting all data we are setting this data in
                        // our text view on below line.
                        pinCodeDetailsTV.setText("Details of pin code is : \n" + "District is : " + district + "\n" + "State : "
                                + state + "\n" + "Country : " + country);
                } catch (JSONException e) {
                    // if we gets any error then it
                    // will be printed in log cat.
                    pinCodeDetailsTV.setText("Pin code is not valid");
        }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
                // below method is called if we get
                // any error while fetching data from API.
                // below line is use to display an error message.
                Toast.makeText(MainActivity.this, "Pin code is not valid.", Toast.LENGTH_SHORT).show();
                pinCodeDetailsTV.setText("Pin code is not valid");
        // below line is use for adding object
        // request to our request queue.

Step 5: Add permission for the internet in the Manifest file

Navigate to the app > AndroidManifest.xml file and add the below permissions to it. 

<uses-permission android:name=”android.permission.INTERNET”/>


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads