Android Tabs Example by using Android Design Support Library

Wth the help of this Android tutorial we will create tab layout with swipe views.The new APIs for android tabs released the design support library and the main class used for displaying tabs through these new APIs is Android TabLayout.In Android Tab example we will create a screen with three tabs using these new APIs for tabs with Fragments and a ViewPager which would look like the image below




1.How to Create Material Design Toolbar click on blow link
link  
http://goo.gl/sUpiZs

2.Add Dependencies

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'
}

3.Create Three Fragment Class for three TAB
Extend Fragment class we will create three Fragment class like example blow

3.1. Create first Fragment.
     fragment_first.xml

<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"
     tools:context="info.anroidpoint.materialtabs.fragments.OneFragment">
<TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="one"
     android:textSize="40dp"
     android:textStyle="bold"
android:layout_centerInParent="true"/>

</RelativeLayout>

OneFragment.java

package info.androidpoint.materialtabs.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import info.androidpoint.materialtabs.R;
public class OneFragment extends Fragment{
    public OneFragment() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
  // Inflate the layout 
  return inflater.inflate(R.layout.fragment_one, container, false);
    }

}

3.2 create second Fragment
fragment_two.xml

<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"
     tools:context="info.anroidpoint.materialtabs.fragments.TwoFragment">
<TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="two"
     android:textSize="40dp"
     android:textStyle="bold"
    android:layout_centerInParent="true"/>

</RelativeLayout>

TwoFragment.java

package info.androidpoint.materialtabs.fragments;

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

import info.androidpoint.materialtabs.R;


public class
TwoFragment extends Fragment{

    public TwoFragment() {
        // public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       // Inflate the layout
        return inflater.inflate(R.layout.fragment_two, container, false);
    }


}


3.3 create third Fragment
fragment_three,xml

<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"
     tools:context="info.anroidpoint.materialtabs.fragments.ThreeFragment">
<TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="two"
     android:textSize="40dp"
     android:textStyle="bold"
    android:layout_centerInParent="true"/>

</RelativeLayout>

ThreeFragment,java

package info.androidpoint.materialtabs.fragments;

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

import info.androidpoint.materialtabs.R;


public class
ThreeFragment extends Fragment{

    public ThreeFragment() {
        
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout 
        return inflater.inflate(R.layout.fragment_three, container, false);
    }


}


4. Create XML for MainActivity

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"      
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>


5.Create MainActivity  class

package info.androidpoint.materialtabs.activity;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

import info.androidpoint.materialtabs.R;
import info.androidpoint.materialtabs.fragments.OneFragment;
import info.androidpoint.materialtabs.fragments.ThreeFragment;
import info.androidpoint.materialtabs.fragments.TwoFragment;


public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new
ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new OneFragment(), "ONE");
        adapter.addFragment(new TwoFragment(), "TWO");
        adapter.addFragment(new ThreeFragment(), "THREE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

}






JSON and XML Parsing in Android

1. JSON

First we talk about basic knowledge of JSON.
JSON stands for JavaScript Object Notation,it's a lightweight data-interchange format. It is easy for user to read and write.
whenever we want to use JSON parsing for should know about JSON syntax like 

 name/value pairs,separated by commas,Curly braces for hold array
there are five type values use in JSON Array,Boolean,Number,Object,String
1.Json Arrray:-JSONArray to parse JSON which is starts brackets ([ ]) of Array.for  example [{"item1":"value1"},{"item2": "value2"} ]
2.Josn Object:-it's begins with curly braces ({ }) and use to contain key/value pairs. for example {"item1":"value1"},{"item2": "value2"}
3.if we talk about json in deep the json can be nested inside one another for example
{"jsonObject": 0, "jsonArray":  [{"item1":"value1"},{"item2": "value2"}] }

Let,s we talk about JSON Parsing with GET and POST method in Android.

1.Create HTTP Connection for getting response from server with GET Method 

public static String findJSONFromUrl(String url) {
String result = "";
try {
         URL urls = new URL(url);
         HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
         conn.setReadTimeout(150000);/* milliseconds */
         conn.setConnectTimeout(15000); /* milliseconds */
         conn.setRequestMethod("GET");
         conn.connect();
         BufferedReader reader = new BufferedReader(new InputStreamReader(
         conn.getInputStream(), "iso-8859-1"), 8);
         StringBuilder sb = new StringBuilder();
         String line = null;

    while ((line = reader.readLine()) != null)
       {
               sb.append(line + "\n");
        }
              result = sb.toString();
catch (Exception e) {
 // System.out.println("exception in jsonparser class ........");
      e.printStackTrace();
return null;
}
return result;
 } // method ends 




2.Create HTTP Connection for getting response from server with POST Method 


//  create ArrayLiat for your params
ArrayList param= new ArrayList<>();
param.add("key1"="Your Value1");
param.add("&key2"="Your Value2");
param.add("&key3"="Your Value3") ;                                                                                   

//This is a methid for post data on server and get responce     
public static String postData(String url, ArrayList<String> params) {       
// TODO Auto-generated method stub
String response = "";
  try {
          URL urls = new URL(url);
          HttpURLConnection con = (HttpURLConnection) urls.openConnection();
          con.setConnectTimeout(15000);
          con.setReadTimeout(15000);
          con.setDoInput(true);
          con.setDoOutput(true); // true indicates POST request
          con.setRequestMethod("POST");
          con.connect();
    if (con != null) {
        // TODO: write or sends POST data in form of byte
    try {
            StringBuffer requestParams = new StringBuffer();
            String value = "";
           if (params != null && params.size() > 0) {
           // creates the params string, encode them using URLEncoder
              Iterator<String> paramIterator = params.iterator();
              while (paramIterator.hasNext()) {
             value = paramIterator.next();
             // Convertin arraylist value inform of bytes
    try {
            DataOutputStream wr = new DataOutputStream(
            con.getOutputStream());
            wr.writeBytes(value);
            wr.flush();
    catch (Exception e) {
         e.printStackTrace();
          }
    }

if (con.getResponseCode() == HttpURLConnection.HTTP_OK && con != null) {
         BufferedReader bufferedReader = new BufferedReader(
         new InputStreamReader(con.getInputStream()));
         StringBuilder stringBuilder = new StringBuilder();
         String data;
      while ((data = bufferedReader.readLine()) != null) {
          stringBuilder.append(data + "\n");

            }
            response = stringBuilder.toString();
         }
     }
         con.disconnect();
     }
   catch (Exception e) {
       e.printStackTrace();
  }
 return response;
}// method ends 

4.After getting responce from server get data from JSONArray
suppose responce :-
{"jsonObject": 0,"jsonArray":  [{"item1":"value1"},{"item2": "value2"},{"item3": "value3"}] }

JSONArray jsonArray = new JSONArray("jsonArray");
   if (jsonArray != null) {
        for (int i = 0; i < jsonArray.length(); i++) {
      JSONObject     jsonObject = jsonArray.getJSONObject(i);
      String  value1 = jsonObject.getString("item1");
      String  value2 = jsonObject.getString("item2");
      String  value3 = jsonObject.getString("item3");
}
}

5.After getting response from server get data from JSONObject 
 JSONObject     jsonObject = new JSONObject("Object Name");
      String  value1 = jsonObject.getString("your key1");
      String  value2 = jsonObject.getString("your key2");
      String  value3 = jsonObject.getString("your key3");


2.XML
First we'll Know about 'what is XML?'
XML is a EXtensible Markup Language and it was design to describe data;
XML tags are not predefined. You must define your own tags; 

XML Parsing
with the help of XmlPullParser to parse XML in Android.there are following methods to parse XML
Method startDocument() :- Method called at the start of an XML document.
Method endDocument()  :-  Method called at  end of an XML document.
Method startElement() :-Method called at the start of a document element.
Method endElement()  :- Method called at  end of a document element.  

characters() – Method called with the text contents in between the start and end tags of an XML document element.

Here an Example of XML parsing
try {
    XmlPullParserFactory xmlfact = XmlPullParserFactory.newInstance();  
    xmlfact.setNamespaceAware(true);
    XmlPullParser parser = xmlfact.newPullParser();
    StringReader sr = new StringReader(result);
    parser.setInput(sr);
      int eventtype = parser.getEventType(); 
      String tag1="";
      String tag2="";
  while(eventtype!=XmlPullParser.END_DOCUMENT)
  {
     if(eventtype==XmlPullParser.START_TAG && parser.getName().equals("item"))
    {
       eventtype = parser.next();
     while(true)
      {
         if(eventtype==XmlPullParser.END_TAG && parser.getName().equals("item"))
          break;
          if(eventtype==XmlPullParser.START_TAG &&                                                                parser.getName().equals("title"))
          {
             eventtype = parser.next();
              tag1 = parser.getText();
           }
         if(eventtype==XmlPullParser.START_TAG &&                                                                   parser.getName().equals("link"))
          {
        eventtype = parser.next();
        tag2 = parser.getText();
      }
     eventtype = parser.next();
    }
         Score sc = new Score(tag1, tag2);
         list.add(sc);
         adp.notifyDataSetChanged();
    }
        eventtype = parser.next();
  }
 } catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}