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

Multiple fragments in one activity example

Create New project Multiple Fragment with empty activity

// activity_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.multiplefragment.MainActivity">

    <FrameLayout android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/container" >
    </FrameLayout>
</LinearLayout>
// fragment-login.xml
<LinearLayout 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:orientation="vertical"
    tools:context="com.krishanandroid.multiplefragment.MainActivity">

    <EditText 
       android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="enter email"
        android:id="@+id/editText1"
        android:textSize="24sp"
        android:gravity="center_horizontal"
        android:textColor="@color/colorAccent"/>

    <EditText
        android:layout_width="match_parent" 
       android:layout_height="wrap_content"
        android:hint="enter password"
        android:id="@+id/editText2"
        android:textSize="24sp"
        android:gravity="center_horizontal"
        android:textColor="@color/colorAccent"/>


    <Button 
       android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button1"
        android:text="Login"
        android:layout_gravity="center"
        android:textSize="16sp"/>

</LinearLayout>
// fragment_welcome.xml
<LinearLayout 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:orientation="vertical"
    tools:context="com.krishanandroid.multiplefragment.MainActivity">

    <TextView 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content"
        android:id="@+id/textView1"
        android:text="Welcome user"
        android:textSize="24sp"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:text="Your name is: "
        android:textSize="24sp"/>

</LinearLayout>
//WelcomeFragment.java
package com.krishanandroid.multiplefragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class WelcomeFragment extends Fragment {

    TextView mTv1, mTv2;

    public WelcomeFragment() {
        // Required empty public constructor    }

       @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment        
View view = inflater.inflate(R.layout.fragment_welcome, container, false);
        mTv1 = view.findViewById(R.id.textView1);
        mTv2 = view.findViewById(R.id.textView2);

        Bundle bundle = getArguments();
        if (bundle!=null)
        {
            String email = bundle.getString("email");
            String pwd = bundle.getString("pwd");

            mTv1.setText("Hi "+email);
            mTv2.setText("Pwd: "+pwd);
        }
        return view;
    }
}
// LoginFragment.java
package com.krishanandroid.multiplefragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class LoginFragment extends Fragment {

    EditText        mEmail, mPassword;
    Button          mButtonLogin;

    public LoginFragment() {
        // Required empty public constructor    }

    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment       
 View view = inflater.inflate(R.layout.fragment_login, container, false);

        mEmail = view.findViewById(R.id.editText1);
        mPassword = view.findViewById(R.id.editText2);
        mButtonLogin = view.findViewById(R.id.button1);

        mButtonLogin.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                String email = mEmail.getText().toString();
                String pwd = mPassword.getText().toString();

                MainActivity m = (MainActivity) getActivity();
                m.loadWelcome(email, pwd);
            }
        });
        return view;
    }

}

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

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    FragmentManager                 fragmentManager;
    FragmentTransaction             fragmentTransaction;

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

        fragmentManager = getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();

        LoginFragment loginFragment = new LoginFragment();
        Bundle bundle = new Bundle();
        loginFragment.setArguments(bundle);

        fragmentTransaction.add(R.id.container,loginFragment);
        fragmentTransaction.commit();

    }

    public void loadWelcome(String email, String pwd) {

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction  fragmentTransaction = manager.beginTransaction();

        WelcomeFragment welcomeFragment = new WelcomeFragment();

        Bundle bundle = new Bundle();
        bundle.putString("email",email);
        bundle.putString("pwd",pwd);
        welcomeFragment.setArguments(bundle);
        fragmentTransaction.replace(R.id.container,welcomeFragment);
        fragmentTransaction.addToBackStack(null); // Back button correctly        fragmentTransaction.commit();
    }
}

Live Demo: https://www.youtube.com/watch?v=vgReN-zmXnQ