How to Build a Weather App in Android?
In this project, we will be building a weather application. This application will show the temperature of a location. To fetch weather information we will need an API. An API(Application Programming Interface) is a function that allows applications to interact and share data using various components and microservices. For this project, we will be using WeatherBit API for fetching weather data. WeatherBit API provides a fast and elegant way to fetch weather data. Note that we are going to implement this project using the Kotlin language.
Project Overview
In this project, we will build an app that will find the device’s location coordinates(longitude and latitude). Then we will send this data to the API via an API key(which we will see later). The API will send us a JSON from which we will extract the required data that is the temperature and city of the location.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Before going to the coding section first you have to do some pre-task
Go to the app > res > drawable file and paste this image to this file. Now right-click on the drawable folder > New > Drawable resource File and name the file as btn_bg6. Below is the code for the btn_bg6.xml file.
Reference Article: How to Add Image to Drawable Folder in Android Studio?
XML
<? xml version = "1.0" encoding = "utf-8" ?> < selector xmlns:android = "http://schemas.android.com/apk/res/android" > < item > < shape > < gradient android:angle = "0" android:startColor = "#BBE1FD" android:endColor = "#6CC7E3" android:type = "linear" /> </ shape > </ item > </ selector > |
Step 3: Get the API key
To get the API key simply sign-in on WeatherBit and subscribe for a free API of Current Weather Data API. After doing so you will receive an API key and you are good to go.
Step 4: Permission Check
For this app to work we need to ask for three permissions from the system –
- Coarse Location – <uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/>
- Fine Location – <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION”/>
- Internet – <uses-permission android:name=”android.permission.INTERNET”/>
We will add code for use permission in the AndroidManifest.xml file. See the below code
XML
<? xml version = "1.0" encoding = "utf-8" ?> < manifest xmlns:android = "http://schemas.android.com/apk/res/android" <uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION" /> < uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION" /> < uses-permission android:name = "android.permission.INTERNET" /> < application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme" > < activity android:name = ".MainActivity" > < intent-filter > < action android:name = "android.intent.action.MAIN" /> < category android:name = "android.intent.category.LAUNCHER" /> </ intent-filter > </ activity > </ application > </ manifest > |
Step 5: Building the Layout
We will add a Button and TextView in the one and only screen of the application. When the user will click the Button the temperature and city of that location will be shown in the TextView. See the code below:
XML
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout 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:background = "@drawable/weather_background" tools:context = ".MainActivity" > < Button android:id = "@+id/btVar1" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_centerInParent = "true" android:background = "@drawable/btn_bg6" android:padding = "10dp" android:text = "Get Weather" android:textSize = "20dp" /> < TextView android:id = "@+id/textView" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_margin = "40dp" android:layout_marginBottom = "100dp" android:fontFamily = "sans-serif-black" android:text = "Get temperature here" android:textColor = "#F6F8F5" android:textSize = "25dp" android:textStyle = "bold" /> </ RelativeLayout > |
Step 6: Getting Device’s Coordinates
In this step, we will get the last location of the device using Google Play Services –
- Setup google play services by downloading its components in the SDK manager.
- Add dependency in build.gradle for location – “implementation com.google.android.gms:play-services-location:17.1.0″, the version might change later.
- In the onCreate() method create an instance of the Fused Location Provider Client.
- After this use lastlocation() method to call the last location. See the Kotlin code after Step 5.
Step 7: Parse JSON after getting it
To get JSON we need to use Volley Library to make an HTTP client request
- Add ‘implementation com.android.volley:volley:1.1.1’ to the gradle app file.
- Create the http for the JSON. For example – “https://api.weatherbit.io/v2.0/current?” + “lat=” + location?.latitude +”&lon=”+ location?.longitude + “&key=”+ api_id1. Here we have already generated API key as well as the location coordinates.
- Make a request from this URL and get the data.
Step 8: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.annotation.SuppressLint import android.location.Location import android.os.Bundle import android.util.Log import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.android.volley.Request import com.android.volley.Response import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import kotlinx.android.synthetic.main.activity_main.* import org.json.JSONObject class MainActivity : AppCompatActivity() { // weather url to get JSON var weather_url1 = "" // api id for url var api_id1 = "030314b750cc43e7b39e503dfe37150c" private lateinit var textView: TextView private lateinit var fusedLocationClient: FusedLocationProviderClient override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) // link the textView in which the // temperature will be displayed textView = findViewById(R.id.textView) // create an instance of the Fused // Location Provider Client fusedLocationClient = LocationServices.getFusedLocationProviderClient( this ) Log.e( "lat" , weather_url1) // on clicking this button function to // get the coordinates will be called btVar1.setOnClickListener { Log.e( "lat" , "onClick" ) // function to find the coordinates // of the last location obtainLocation() } } @SuppressLint ( "MissingPermission" ) private fun obtainLocation() { Log.e( "lat" , "function" ) // get the last location fusedLocationClient.lastLocation .addOnSuccessListener { location: Location? -> // get the latitude and longitude // and create the http URL weather_url1 = "https://api.weatherbit.io/v2.0/current?" + "lat=" + location?.latitude + "&lon=" + location?.longitude + "&key=" + api_id1 Log.e( "lat" , weather_url1.toString()) // this function will // fetch data from URL getTemp() } } fun getTemp() { // Instantiate the RequestQueue. val queue = Volley.newRequestQueue( this ) val url: String = weather_url1 Log.e( "lat" , url) // Request a string response // from the provided URL. val stringReq = StringRequest(Request.Method.GET, url, Response.Listener<String> { response -> Log.e( "lat" , response.toString()) // get the JSON object val obj = JSONObject(response) // get the Array from obj of name - "data" val arr = obj.getJSONArray( "data" ) Log.e( "lat obj1" , arr.toString()) // get the JSON object from the // array at index position 0 val obj2 = arr.getJSONObject( 0 ) Log.e( "lat obj2" , obj2.toString()) // set the temperature and the city // name using getString() function textView.text = obj2.getString( "temp" ) + " deg Celsius in " + obj2.getString( "city_name" ) }, // In case of any error Response.ErrorListener { textView!!.text = "That didn't work!" }) queue.add(stringReq) } } |
Output:
Note: Before running the application make sure the location in the device is turned on and the application has access to that.
GitHub link: https://github.com/njdunk07/NJ-Weather-GFG
Contact Us