How to Get City and State Name from Pincode in Android?
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.
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.
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
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.