Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaHow to Get City and State Name from Pincode in Android?

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. 

implementation ‘com.android.volley:volley:1.1.1’

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




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--heading text view-->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:text="Pin code validator"
        android:textAlignment="center"
        android:textColor="@color/purple_500"
        android:textSize="30sp" />
     
    <!-- edit text for entering our pin code
         we are specifying input type as number-->
    <EditText
        android:id="@+id/idedtPinCode"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:hint="Enter pin code"
        android:importantForAutofill="no"
        android:inputType="number"
        android:maxLines="1"
        android:singleLine="true" />
     
    <!--button to get the data from pin code-->
    <Button
        android:id="@+id/idBtnGetCityandState"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp"
        android:text="Get city and state"
        android:textAllCaps="false" />
     
    <!--text view to display the data
        received from pin code-->
    <TextView
        android:id="@+id/idTVPinCodeDetails"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:padding="10dp"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="@color/purple_500"
        android:textSize="20sp" />
 
</LinearLayout>


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.

Java




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 androidx.appcompat.app.AppCompatActivity;
 
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
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 {
    // 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;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // initializing our variables.
        pinCodeEdt = findViewById(R.id.idedtPinCode);
        getDataBtn = findViewById(R.id.idBtnGetCityandState);
        pinCodeDetailsTV = findViewById(R.id.idTVPinCodeDetails);
         
        // 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() {
            @Override
            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.
                    getDataFromPinCode(pinCode);
                }
            }
        });
    }
 
    private void getDataFromPinCode(String pinCode) {
         
        // clearing our cache of request queue.
        mRequestQueue.getCache().clear();
         
        // below is the url from where we will be getting
        // our response in the json format.
        String url = "http://www.postalpincode.in/api/pincode/" + 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>() {
            @Override
            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.
                    e.printStackTrace();
                    pinCodeDetailsTV.setText("Pin code is not valid");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            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.
        queue.add(objectRequest);
    }
}


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”/>

Output:

RELATED ARTICLES

Most Popular

Recent Comments