How to make Simple Weather Application in Android Studio

How to make Simple Weather Application in Android Studio (Source code)

Demo:


Introduction

In this article, we will learn to create simple weather application in android studio. 

Weather application

We will build a simple weather application which will search for the weather condition in a particular city. For this, we will use API from openweatherorg.com.

The following are some steps we need in order to make this application.
  1. Need weather API
  2. Retrieve data in JSON format from API
  3. Filter JSON response
  4. Display data on screen

Need weather API

You can simply generate your own APIID from openweatherorg.com
API ID Example: https://openweathermap.org/data/2.5/weather?q=London&appid=b6907d289e10d714a6e88b30761fae22
Note: Above key may be expired so generate your own and check as it working before using and don't forget to remove the "sample" word from a link you will get.

Retrieve data in JSON format from API


 AsyncTask<String,Void,String>
i) First String means URL is in String
ii) Void mean nothing
iii) Third String mean return type will be String

The following class will read the content of API.

      class Weather extends AsyncTask<String,Void,String>{  
        @Override
        protected String doInBackground(String... address) {
            //String... means multiple address can be send. It acts as array
            try {
                URL url = new URL(address[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //Establish connection with address
                connection.connect();

                //retrieve data from url
                InputStream is = connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);

                //Retrieve data and return it as String
                int data = isr.read();
                String content = "";
                char ch;
                while (data != -1){
                    ch = (char) data;
                    content = content + ch;
                    data = isr.read();
                }
                return content;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
    }
In order to read data from API with the help of the above class. We can call it simply like below

Weather weather = new Weather();
String content = weather.execute("https://openweathermap.org/data/2.5/weather?q=" +
yourcitynamehere+"&appid=b6907d289e10d714a6e88b30761fae22").get();
//Log the data
Log.i("contentData",content);

Filter JSON response

Now, we will filter "main, description, temperature, and visibility" from retried JSON (stored in content variable ).

JSONObject jsonObject = new JSONObject(content);
String weatherData = jsonObject.getString("weather");
String mainTemperature = jsonObject.getString("main");
double visibility;
//weather data is in Array
JSONArray array = new JSONArray(weatherData);

String main = "";
String description = "";
String temperature = "";

for(int i=0; i<array.length i++){
   JSONObject weatherPart = array.getJSONObject(i);
   main = weatherPart.getString("main");
   description = weatherPart.getString("description");
}

JSONObject mainPart = new JSONObject(mainTemperature);
temperature = mainPart.getString("temp");

visibility = Double.parseDouble(jsonObject.getString("visibility"));
//By default visibility is in meter
int visibiltyInKilometer = (int) visibility/1000;  

Display data on the screen

In the above section, we retrieve "main, description, temperature, and visibility", now we will simply arrange them in string variable and display on the screen.

String resultText = "Main :"+main+
"\nDescription :"+description +
"\nTemperature :"+temperature +"*C"+
"\nVisibility :"+visibiltyInKilometer+" KM";
Now, initialize TextView and set the value to it.

TextView textview;

textview = findViewById(R.id.textview);
//now set value
textview.setText(resultText);

That's it. Following is the complete code. Have a look

MainActivity.java

package com.example.weatherapplication;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    class Weather extends AsyncTask{  //First String means URL is in String, Void mean nothing, Third String means Return type will be String

        @Override
        protected String doInBackground(String... address) {
            //String... means multiple address can be send. It acts as array
            try {
                URL url = new URL(address[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                //Establish connection with address
                connection.connect();

                //retrieve data from url
                InputStream is = connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);

                //Retrieve data and return it as String
                int data = isr.read();
                String content = "";
                char ch;
                while (data != 0){
                    ch = (char) data;
                    content = content + ch;
                    data = isr.read();
                }
                Log.i("Content",content);
                return content;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i("HEllo World","whats'up");

        String content;
        Weather weather = new Weather();
        try {
            content = weather.execute("https://openweathermap.org/data/2.5/weather?q=London&appid=b6907d289e10d714a6e88b30761fae22").get();
            //First we will check data is retrieve successfully or not
            Log.i("contentData",content);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/weather"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/cityName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="92dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="45dp"
        android:ems="10"
        android:gravity="center"
        android:hint="Enter city name"
        android:inputType="textPersonName"
        android:textColor="@android:color/black"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/searchButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/searchButton"
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:layout_marginBottom="60dp"
        android:onClick="search"
        android:text="search"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/resut"
        app:layout_constraintEnd_toEndOf="@+id/cityName"
        app:layout_constraintStart_toStartOf="@+id/cityName"
        app:layout_constraintTop_toBottomOf="@+id/cityName" />

    <TextView
        android:id="@+id/resut"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:padding="8dp"
        android:textColor="#FF000000"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="@+id/searchButton"
        app:layout_constraintStart_toStartOf="@+id/searchButton"
        app:layout_constraintTop_toBottomOf="@+id/searchButton" />
</android.support.constraint.ConstraintLayout>

Add permision to AndroidManifest.xml

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

Comments

  1. This source code is missing a lot and unfortunately even after following the video tutorial it's not working properly. Is there an updated version of the code?

    ReplyDelete
    Replies
    1. while (data != 0){ replace by while (data > 0){

      Delete
    2. Hi, So sorry for late reply. Did this line resolve your issue or you need help?

      Delete
  2. you waste my time this code is incorrect and incomplete

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. while (data != 0){ replace by while (data > 0){

      Delete
    3. Hi, So sorry for late reply. I checked the code and it's working fine on my side. Here is the repo: https://github.com/abdullah432/WeatherApp
      If still issue. Send me error your getting. I will try to help

      Delete
  3. THANKYOU. Really Helpful. Awesome Description.

    ReplyDelete

Post a Comment