Open In App

Android – Get Time Zone of a Given Location using Rapid API

Last Updated : 04 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

RapidAPI platform is a multi-cloud, customized hub to find, connect to, and share APIs. The API Platform improves the developer experience with integrated tools for designing, testing, monitoring, building, publishing APIs, and more.

In this article, we will create one Android application in Android Studio by using Java and one RapidAPI. This article shows you how to use RapidAPI in Android App. You can use this code structure to apply any Rapid API related projects in Android App. Basically, Rapid API provides lots of Free as well-paid APIs that are very useful in our real-life projects. So, this will be very helpful article for the use example of Rapid API in Android App using Java.

Rapid API Basically provides Free, Freemium, and Paid various types of API. 40,000+ APIs available here. You can use any type of API that’s needed in your projects.

Step By Step Implementation

Step 1: Create a New Project

Open Android Studio and create a new Android project there. Then set the project name and project language as Java. And if you need any help regarding creating a new project, prefer this How to create project in Android Studio using Kotlin.

Step 2: Adding the dependency to the build.gradle(:app) file

implementation(“com.squareup.okhttp3:okhttp:4.9.3”)

Here we used OkHttp. HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth. Using OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks.

Step 3: Working with the AndroidManifest.xml file to add these two permission

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

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

Step 4: Working with the activity_main.xml file to change the layout

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical">
  
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:textSize="30sp"
            android:textColor="#2b8e44"
            android:textStyle="bold"
            android:layout_marginBottom="20dp"
            android:gravity="center_horizontal"
            android:text="Use Rapid API\nGeeks-for-Geeks"/>
  
        <EditText
            android:id="@+id/input1"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:hint="Enter the Area Name"
            android:layout_margin="20dp"/>
  
        <EditText
            android:id="@+id/input2"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:hint="Enter the Location Name"
            android:layout_margin="20dp"/>
  
        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/button"
            android:layout_width="250dp"
            android:layout_height="60dp"
            android:background="#2b8e44"
            android:layout_marginTop="10dp"
            android:text="Retrieve Time Zone"
            android:textSize="20sp"
            android:textColor="@android:color/white"
            android:textAllCaps="false"
            android:layout_gravity="center_horizontal"/>
  
        <TextView
            android:id="@+id/result_show"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textColor="@android:color/black"
            android:layout_marginTop="25sp"
            android:layout_gravity="center_horizontal"
            android:textSize="25sp"/>
    </LinearLayout>
    
</RelativeLayout>


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

Java




package gfgtestingbyamit.example.gfgtesting;
  
import androidx.appcompat.app.AppCompatActivity;
  
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
  
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
  
import java.io.IOException;
  
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
  
public class MainActivity extends AppCompatActivity {
      
    TextView textView;
    Button button;
    EditText editText1,editText2;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.result_show);
        button = findViewById(R.id.button);
        editText1 = findViewById(R.id.input1);
        editText2 = findViewById(R.id.input2);
          
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s1 = editText1.getText().toString();
                String s2 = editText2.getText().toString();
                fetchData(s1,s2);
            }
        });
          
    }
    private void fetchData(String string1, String string2) {
        String url = "https://world-time2.p.rapidapi.com/timezone/"+string1+"/"+string2;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("X-RapidAPI-Key", "Put Your Key Here.......")
                .addHeader("X-RapidAPI-Host", "world-time2.p.rapidapi.com")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                final Toast toast = Toast.makeText(MainActivity.this, "GAME OVER!\nScore: " , Toast.LENGTH_SHORT);
                toast.show();
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
  
                if (response.isSuccessful()){
                    String resp = response.body().string();
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Toast.makeText(MainActivity.this, "ddff", Toast.LENGTH_SHORT).show();
                                JSONObject jsonObject = new JSONObject(resp);
                                String val1 =  jsonObject.getString("datetime");
                                textView.setText(val1);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
  
            }
        });
    }
}


Output:

953d7072-6cf8-4515-a9b1-d9bb9f543f65

Output

You can use the same Rapid API template with any of your projects that use Rapid API.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads