Weather app

How to make a weather App in android

In this article, I will show you guys how to make a weather app in android using open weather API.

But before we start take a look at, how our app will look.

app

Without wasting any further time let’s get started with it! Every step is commented out in the source code with an explanation of what that piece of code do and why it is there and you’re free to use the code for whatever purpose you want to.

 

Main Activity File

package com.example.varmee.weatherapp;

// importing Packages which we will need for this app

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

// Main activity class
public class MainActivity extends AppCompatActivity {

    TextView result1;

    EditText cityName;

    // This method would be called when What's the weather button would be pressed
    public void findtheweather(View view) {

        //Assigning the value which user entered to String s
        String s = cityName.getText().toString();

        // Calling download task function
        download task = new download();

        // Executing download task and change this " uk&appid=9f681051b003f104ae5e2a0cbef19a02" with your own API KEY
        task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + s + "uk&appid=9f681051b003f104ae5e2a0cbef19a02");

    }

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

        // Using id to tell where to make changes
        cityName = (EditText) findViewById(R.id.cityname);


    }

    // Creating download method with Async Task ( we r going to use this to get data from internet and parse it )
    private class download extends AsyncTask<String, Void, String> {

        // This method execute after doInBackground method and Parse the Json

        @Override
        protected void onPostExecute(String result) {
// Try and catch block to catch any errors
            try {

                // linking result1 with textView with id result
                result1 = (TextView) findViewById(R.id.result);

//                calling  JSONObject as jsonObject
                JSONObject jsonObject = new JSONObject(result);

//                using jsonObject to get String from Json which is tagged as weather
                String weather = jsonObject.getString("weather");
//        calling JSONArray as arr
                JSONArray arr    = new JSONArray(weather);
// using for loop to loop through arr array
                for (int i = 0; i <= arr.length(); i++) {

                    JSONObject jsonPart = arr.getJSONObject(i);

                    // using result1 to set Text of that Text view with id Result  to this
                    result1.setText(String.format("Weather : %s , Description : %s", jsonPart.getString("main"), jsonPart.getString("description")));
                }

//                e.printStackTrace will just print a error report like a normal program do when it crashes u can change this with anything u like
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        // do doInBackground method we r using this method to download Json from site.
        @Override
        protected String doInBackground(String... urls) {
            String result = "";

//            calling url as url
            URL url;
//            calling HttpUrlConnection as urlConnection
            HttpURLConnection urlConnection;

//            Using try and catch block to find any errors
            try {
                // assigning url value of first object in array called urls which is declared in this start of this method
                url = new URL(urls[0]);

                // using urlConnection to open url which we assigning URL before
                urlConnection = (HttpURLConnection) url.openConnection();

                // Using InputStream to download the content
                InputStream inputStream = urlConnection.getInputStream();
                // Using InputStreamReader to read the inputstream or the data we r downloading
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

//                using it to check if we reached the end of String / Data
                int Data = inputStreamReader.read();
//              using While loop to assign that data to string called result because InputStreamReader reads only one character at a time
                while (Data != -1) {

                    char current = (char) Data;

                    result += current;

                    Data = inputStreamReader.read();
                }

                // returning value of result

                return result;

//                Try and catch block to catch any errors
            } catch (Exception e) {
//                e.printStackTrace will just print a error report like a normal program do when it crashes u can change this with anything u like
                e.printStackTrace();
            }

            return null;
        }


    }

}

 

Layout / activity_main file

 

<?xml version="1.0" encoding="utf-8"?>

<!--Layout File-->

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.varmee.weatherapp.MainActivity"
    android:background="@drawable/download">

<!-- Setting the Image which we wanna use for Background of our app-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter a City"
        android:textSize="50dp"
        android:textColor="@color/colorPrimary"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:layout_width="230dp"
        android:layout_height="45dp"
        android:id="@+id/cityname"
        android:layout_below="@+id/textView"
        android:layout_alignLeft="@+id/textView"
        android:layout_alignStart="@+id/textView"
        android:layout_marginTop="45dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="What's the weather."
        android:id="@+id/button"
        android:onClick="findtheweather"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <!--using onClick to call the method we codded in main Activity earlier -->

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/result"
        android:layout_marginTop="74dp"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

 

ManifestFile

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.varmee.weatherapp" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>

    <!-- Asking for permission from os to use Internet-->

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

</manifest>

Don’t forget to comment and share if you liked it!

Link to source code : https://drive.google.com/open?id=0BzGnrTJ6GBIlQVI5Smd0LTFZUHc

Password : Codegeek.io

Suggestions are always welcome 🙂 please don’t forget to comment, if you want us to change something.

Leave a Reply