Tuesday, 16 October 2018

Open Weather Project with JSON Rest web service and Network API

Create New project RecyclerView Custom Adapter with empty activity
// android_manifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.krishanandroid.openweatherproject">

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

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

// actvity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="com.krishanandroid.openweatherproject.MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter zipcode"
        android:textSize="16sp"
        android:textColor="@color/colorAccent"
        android:id="@+id/et_zipcode"
        android:padding="12dp"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Check Weather"
        android:textSize="16sp"
        android:id="@+id/button_weather"
        android:padding="12dp"/>

    <TextView
        android:id="@+id/tv_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Main"
        android:padding="12dp"/>

    <TextView
        android:id="@+id/tv_Description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Description"
        android:padding="12dp"/>

    <TextView
        android:id="@+id/tv_temp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Temperature"
        android:padding="12dp"/>

    <TextView
        android:id="@+id/tv_humidity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Humidity"
        android:padding="12dp"/>

    <TextView
        android:id="@+id/tv_country"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Country"
        android:padding="12dp"        />
    <TextView
        android:id="@+id/tv_location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Location"
        android:padding="12dp"/>

</LinearLayout>

// MainActivity.java
package com.krishanandroid.openweatherproject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
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 {

    TextView    mHumidity, mTemp, mCountry, mLocation, mMain, mDesc;

    EditText    mZipCode;
    Button      mCheckWeather;

    MyTask      myTask;

    private class MyTask extends AsyncTask<String, Void, String>{

        URL                 url;
        HttpURLConnection   con;
        InputStream         i;
        InputStreamReader   ir;
        BufferedReader      br;
        String              s;
        StringBuilder       sb;

        @Override        protected String doInBackground(String... strings) {

            try {
                url=new URL(strings[0]);
                con= (HttpURLConnection) url.openConnection();
                i=con.getInputStream();
                ir=new InputStreamReader(i);
                br=new BufferedReader(ir);
                sb=new StringBuilder();
                s=br.readLine();
                while (s!=null){
                    sb.append(s);//add each json line to string builder
                    s=br.readLine();//read each line from buffered reader                }
                //return json to onpost                return sb.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
                Log.d("OWP","URL IS WRONG" + e);
            } catch (IOException e) {
                e.printStackTrace();
                Log.d("OWP","NETWORK PROBLEM" + e);
            }

            return null;
        }

        @Override        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s==null)
            {
                Toast.makeText(MainActivity.this,"No data found",Toast.LENGTH_LONG).show();
                return;
            }

            try {
                JSONObject jsonObject = new JSONObject(s); // Getting data in json object                JSONArray jsonArray = jsonObject.getJSONArray("weather");

                for(int i=0;i<jsonArray.length();i++){

                    JSONObject obj=jsonArray.getJSONObject(i);
                    String main=obj.getString("main");
                    String description=obj.getString("description");
                    mMain.setText("Main: "+main);
                    mDesc.setText("Description: "+description);

                }

                JSONObject main=jsonObject.getJSONObject("main");
                String temp=main.getString("temp");
                String humidity=main.getString("humidity");
                mTemp.setText("Temp: "+temp);             // temperature
                mHumidity.setText("Humidity: "+humidity); // humidity
                JSONObject sys=jsonObject.getJSONObject("sys");
                String country=sys.getString("country"); // set country name
                mCountry.setText("Country: "+country);
                String name=jsonObject.getString("name");
                mLocation.setText("Name: "+name); // set location name
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "Disconnect", Toast.LENGTH_SHORT).show();
            }
        }
    }

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

        // initialize variables        mHumidity = findViewById(R.id.tv_humidity);
        mTemp = findViewById(R.id.tv_temp);
        mCountry = findViewById(R.id.tv_country);
        mLocation = findViewById(R.id.tv_location);
        mMain = findViewById(R.id.tv_main);
        mDesc = findViewById(R.id.tv_Description);

        mZipCode = findViewById(R.id.et_zipcode);
        mCheckWeather = findViewById(R.id.button_weather);

        myTask = new MyTask();
        // button click listener        
mCheckWeather.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                if (checkInternet()==true)
                {
                    String zipcode = mZipCode.getText().toString();
                    myTask.execute("http://api.openweathermap.org/data/2.5/weather?
zip="+zipcode+",in&appid=bae1ba8dfee48b1");
                    mCheckWeather.setEnabled(false);
                }else                {
                    Toast.makeText(MainActivity.this,"No internet",Toast.LENGTH_LONG).show();
                }
            }
        });

    }

    public boolean checkInternet(){
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo!=null && networkInfo.isConnected()== true){
            return true; // internet available        }else{
            return false;//means no internet        }
    }
}
Live Demo: https://www.youtube.com/watch?v=5neuwaL-09Y

No comments:

Post a Comment