Tuesday 6 December 2016

Three Level Exapandable ListView In Android with Two level Indicators

Java:
package zaihuishou.com.expandablerecyclerview;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import zaihuishou.com.expandablerecyclerview.loader.listener.ServiceResponseListener;
import zaihuishou.com.expandablerecyclerview.loader.manager.ServiceManager;
import zaihuishou.com.expandablerecyclerview.navcategory.FirstLevelCategory;
import zaihuishou.com.expandablerecyclerview.navcategory.NavigationGategoryBaseResponse;
import zaihuishou.com.expandablerecyclerview.navcategory.SecondLevelCategory;

public class TestActivity extends AppCompatActivity {
    private ExpandableListView expandableListView;
    private Context context;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        context = this;
        expandableListView = (ExpandableListView) findViewById(R.id.mainList);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
            expandableListView.setIndicatorBounds(width - GetPixelFromDips(50), width - GetPixelFromDips(10));
        } else {
            expandableListView.setIndicatorBoundsRelative(width - GetPixelFromDips(50), width - GetPixelFromDips(10));
        }
        addNavigationList();
    }

    public int GetPixelFromDips(float pixels) {
        // Get the screen's density scale        final float scale = getResources().getDisplayMetrics().density;
        // Convert the dps to pixels, based on density scale        return (int) ((scale * pixels + 0.5f) - 5);
    }

    public void addNavigationList() {
        ServiceManager.navigationList(getApplicationContext(), new ServiceResponseListener<NavigationGategoryBaseResponse>() {
                    @Override                    public void onSuccess(NavigationGategoryBaseResponse response) {
                        expandableListView.setAdapter(new TestActivity.ParentLevel(context, response.getMainCategories()));
                    }

                    @Override                    public void onFailure(Throwable throwable, String errorResponse) {

                    }
                }
        );
    }


    public class ParentLevel extends BaseExpandableListAdapter {

        private Context context;
        private List<FirstLevelCategory> firstLevelCategories;

        public ParentLevel(Context context, List<FirstLevelCategory> firstLevelCategoryList) {
            this.context = context;
            this.firstLevelCategories = firstLevelCategoryList;
        }

        @Override        public Object getChild(int arg0, int arg1) {
            return arg1;
        }

        @Override        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            TestActivity.SecondLevelExpandableListView secondLevelELV = new TestActivity.SecondLevelExpandableListView(TestActivity.this);
            secondLevelELV.setAdapter(new TestActivity.SecondLevelAdapter(context, firstLevelCategories.get(groupPosition).getSubGrouphs().get(childPosition)));
            secondLevelELV.setGroupIndicator(getResources().getDrawable(R.drawable.settings_selector));
            DisplayMetrics metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int width = metrics.widthPixels;
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
                secondLevelELV.setIndicatorBounds(width - GetPixelFromDips(50), width - GetPixelFromDips(10));
            } else {
                secondLevelELV.setIndicatorBoundsRelative(width - GetPixelFromDips(50), width - GetPixelFromDips(10));
            }
            return secondLevelELV;
        }

        @Override        public int getChildrenCount(int groupPosition) {
            return firstLevelCategories.get(groupPosition).getSubGrouphs().size();
        }

        @Override        public Object getGroup(int groupPosition) {
            return groupPosition;
        }

        @Override        public int getGroupCount() {
            return firstLevelCategories.size();
        }

        @Override        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override        public View getGroupView(int groupPosition, final boolean isExpanded, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.row_first, null);
                TextView text = (TextView) convertView.findViewById(R.id.eventsListEventRowText);
                final ImageView icon = (ImageView) convertView.findViewById(R.id.icon);

                String name = firstLevelCategories.get(groupPosition).getCategoryname();
                if (name.equals(context.getString(R.string.Fancy))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.fancy));
                } else if (name.equals(context.getString(R.string.Women))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.women));
                } else if (name.equals(context.getString(R.string.Office))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.stationary));
                } else if (name.equals(context.getString(R.string.BooksMore))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.books));
                } else if (name.equals(context.getString(R.string.Men))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.businessman));
                } else if (name.equals(context.getString(R.string.DailyNeeds))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.calendar));
                } else if (name.equals(context.getString(R.string.Garments))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.garments));
                } else if (name.equals(context.getString(R.string.BabyKids))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.babykids));
                } else if (name.equals(context.getString(R.string.Fashion))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.fasion));
                } else if (name.equals(context.getString(R.string.Electronics))) {
                    icon.setBackground(context.getResources().getDrawable(R.drawable.elctronics));
                }
                text.setText(name);
            }
            return convertView;
        }

        @Override        public boolean hasStableIds() {
            return true;
        }

        @Override        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }

    public class SecondLevelExpandableListView extends ExpandableListView {


        public SecondLevelExpandableListView(Context context) {
            super(context);
        }

        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(999999, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public class SecondLevelAdapter extends BaseExpandableListAdapter {

        private Context context;
        private SecondLevelCategory secondLevelCategories;

        public SecondLevelAdapter(Context context, SecondLevelCategory secondLevelCategories) {
            this.context = context;
            this.secondLevelCategories = secondLevelCategories;
        }

        @Override        public Object getGroup(int groupPosition) {
            return groupPosition;
        }

        @Override        public int getGroupCount() {
            return 1;
        }

        @Override        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.row_third, null);
                TextView text = (TextView) convertView.findViewById(R.id.eventsListEventRowText);
                text.setText(secondLevelCategories.getSubcategoryname());
            }
            return convertView;
        }

        @Override        public Object getChild(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.row_second, null);
                TextView text = (TextView) convertView.findViewById(R.id.eventsListEventRowText);
                text.setText(secondLevelCategories.getThirdLevelCategoryList().get(childPosition).getLowersubcategoryname());
            }
            return convertView;
        }

        @Override        public int getChildrenCount(int groupPosition) {
            return secondLevelCategories.getThirdLevelCategoryList().size();
        }

        @Override        public boolean hasStableIds() {
            return true;
        }

        @Override        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
}

main.Xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/activity_test"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="zaihuishou.com.expandablerecyclerview.TestActivity"><ExpandableListViewandroid:id="@+id/mainList"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#ffffff"android:groupIndicator="@drawable/settings_selector"android:transcriptMode="alwaysScroll"></ExpandableListView></RelativeLayout>
rowfirst.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="100dp"android:orientation="horizontal"android:padding="10dp"><ImageViewandroid:id="@+id/icon"android:layout_width="25dp"android:layout_height="25dp"android:layout_alignParentLeft="true" /><TextViewandroid:id="@+id/eventsListEventRowText"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_toLeftOf="@+id/plus"android:layout_toRightOf="@+id/icon"android:textColor="@android:color/background_dark"android:textSize="15sp" /></LinearLayout>
rowsecond.xml:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:padding="10dp"><TextViewandroid:id="@+id/eventsListEventRowText"android:layout_width="match_parent"android:layout_height="wrap_content"android:paddingLeft="20dp" /></LinearLayout>

rowthird.xml:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:padding="10dp"><TextViewandroid:id="@+id/eventsListEventRowText"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>


Thursday 10 November 2016

Custom Digital Clock in Android

digitalClockTv = (TextView) findViewById(R.id.digitalClockTv);
countDownTimer = new CountDownTimer(1000000000, 1000) {

    public void onTick(long millisUntilFinished) {
        String hour, minit, sec;
        Calendar c = Calendar.getInstance();
        hour = String.valueOf(c.get(Calendar.HOUR));
        minit = String.valueOf(c.get(Calendar.MINUTE));
        sec = String.valueOf(c.get(Calendar.SECOND));
        int a = c.get(Calendar.AM_PM);
        if (hour.length() == 1) {
            hour = getString(R.string.zero) + hour;
        }
        if (minit.length() == 1) {
            minit = getString(R.string.zero) + minit;
        }
        if (sec.length() == 1) {
            sec = getString(R.string.zero) + sec;
        }
        if (a == Calendar.AM) {
            digitalClockTv.setText(hour + getString(R.string.colon) + minit + getString(R.string.colon) + sec + getString(R.string.am));
        } else {
            digitalClockTv.setText(hour + getString(R.string.colon) + minit + getString(R.string.colon) + sec + getString(R.string.pm));
        }
    }

    public void onFinish() {
    }
};
countDownTimer.start();


Thank You

Monday 3 October 2016

How to hide/show Toolbar when list is scrolling


Working example gif



Adapter:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import gurubhai.fastxpo.restarent.R;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_ITEM = 1;
    private List<String> mItemList;
    public RecyclerAdapter(List<String> itemList) {
        mItemList = itemList;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        if (viewType == TYPE_ITEM) {
            final View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
            return new RecyclerItemViewHolder(view);
        }
        throw new RuntimeException("There is no type that matches the type " + viewType + " + make sure your using types correctly");
    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        RecyclerItemViewHolder holder = (RecyclerItemViewHolder) viewHolder;
        String itemText = mItemList.get(position); // header
        holder.setItemText(itemText);
    }
    public int getBasicItemCount() {
        return mItemList == null ? 0 : mItemList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return TYPE_ITEM;
    }

    @Override
    public int getItemCount() {
        return getBasicItemCount(); //
    }

    public class RecyclerItemViewHolder extends RecyclerView.ViewHolder {

        private TextView mItemTextView;

        public RecyclerItemViewHolder(final View parent) {
            super(parent);
            mItemTextView = (TextView) parent.findViewById(R.id.itemTextView);
        }

        public void setItemText(CharSequence text) {
            mItemTextView.setText(text);
        }
    }
}

MainActivity.java
public class MainActivity extends AppCompatActivity {


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

    private void initToolbar() {
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        setTitle(getString(R.string.app_name));
        mToolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
    }

    private void initViewPagerAndTabs() {
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
        PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
        pagerAdapter.addFragment(ItemSelectionFragment.createInstance(20), getString(R.string.tab_1));
        pagerAdapter.addFragment(ItemSelectionFragment.createInstance(4), getString(R.string.tab_2));
        viewPager.setAdapter(pagerAdapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);
    }

    static class PagerAdapter extends FragmentPagerAdapter {

        private final List<Fragment> fragmentList = new ArrayList<>();
        private final List<String> fragmentTitleList = new ArrayList<>();

        public PagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        public void addFragment(Fragment fragment, String title) {
            fragmentList.add(fragment);
            fragmentTitleList.add(title);
        }

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

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

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

Fragment.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import gurubhai.fastxpo.restarent.R;
import gurubhai.fastxpo.restarent.adapter.RecyclerAdapter;

public class ItemSelectionFragment extends Fragment {


    public final static String ITEMS_COUNT_KEY = "PartThreeFragment$ItemsCount";

    public static ItemSelectionFragment createInstance(int itemsCount) {
        ItemSelectionFragment partThreeFragment = new ItemSelectionFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ITEMS_COUNT_KEY, itemsCount);
        partThreeFragment.setArguments(bundle);
        return partThreeFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        RecyclerView recyclerView = (RecyclerView) inflater.inflate(
                R.layout.fragment_item_selection, container, false);
        setupRecyclerView(recyclerView);
        return recyclerView;
    }

    private void setupRecyclerView(RecyclerView recyclerView) {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        RecyclerAdapter recyclerAdapter = new RecyclerAdapter(createItemList());
        recyclerView.setAdapter(recyclerAdapter);
    }

    private List<String> createItemList() {
        List<String> itemList = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle != null) {
            int itemsCount = bundle.getInt(ITEMS_COUNT_KEY);
            for (int i = 0; i < itemsCount; i++) {
                itemList.add("Item " + i);
            }
        }
        return itemList;
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

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

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabIndicatorColor="@android:color/white"
            app:tabIndicatorHeight="6dp"
            app:tabSelectedTextColor="@android:color/white"
            app:tabTextColor="@android:color/white" />
    </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>

recycler_item.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="8dp"
    card_view:cardCornerRadius="4dp">
    <TextView
        android:id="@+id/itemTextView"
        android:layout_width="match_parent"
        android:layout_height="?attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:padding="8dp"
        style="@style/Base.TextAppearance.AppCompat.Body2"/>
</android.support.v7.widget.CardView>

Gradel:
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'com.android.support:cardview-v7:23.4.0'

Thank you

Wednesday 28 September 2016

Android - JSON Parser Tutorial

Android - JSON Parser Tutorial



JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it.
Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer.
The first step is to identify the fields in the JSON data in which you are interested in. For example. In the JSON given below we interested in getting temperature only.
{
   "sys":
   {
      "country":"GB",
      "sunrise":1381107633,
      "sunset":1381149604
   },
   "weather":[
   {
      "id":711,
      "main":"Smoke",
      "description":"smoke",
      "icon":"50n"
   }
],
"main":
   {
      "temp":304.15,
      "pressure":1009,
   }
}

JSON - Elements

An JSON file consist of many components. Here is the table defining the components of an JSON file and their description −
Sr.NoComponent & description
1Array([)
In a JSON file , square bracket ([) represents a JSON array
2Objects({)
In a JSON file, curly bracket ({) represents a JSON object
3Key
A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object
4Value
Each key has a value that could be string , integer or double e.t.c

JSON - Parsing

For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it. Its syntax is:
String in;
JSONObject reader = new JSONObject(in);
The last step is to parse the JSON. An JSON file consist of different object with different key/value pair e.t.c. So JSONObject has a separate function for parsing each of the component of JSON file. Its syntax is given below:
JSONObject sys  = reader.getJSONObject("sys");
country = sys.getString("country");
   
JSONObject main  = reader.getJSONObject("main");
temperature = main.getString("temp");
The method getJSONObject returns the JSON object. The method getStringreturns the string value of the specified key.
Apart from the these methods , there are other methods provided by this class for better parsing JSON files. These methods are listed below −
Sr.NoMethod & description
1get(String name)
This method just Returns the value but in the form of Object type
2getBoolean(String name)
This method returns the boolean value specified by the key
3getDouble(String name)
This method returns the double value specified by the key
4getInt(String name)
This method returns the integer value specified by the key
5getLong(String name)
This method returns the long value specified by the key
6length()
This method returns the number of name/value mappings in this object..
7names()
This method returns an array containing the string names in this object.

Example

To experiment with this example , you can run this on an actual device or in an emulator.
StepsDescription
1You will use Android studio to create an Android application. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add necessary code.
3Modify the res/layout/activity_main to add respective XML components
4Modify the res/values/string.xml to add necessary string components
5Run the application and choose a running android device and install the application on it and verify the results
Following is the content of the modified main activity filesrc/MainActivity.java.
package com.tutorialspoint.json;

import android.app.Activity;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
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;

public class MainActivity extends Activity {
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      TextView output = (TextView) findViewById(R.id.textView1);
      String strJson="
      {
         \"Employee\" :[
         {
            \"id\":\"01\",
            \"name\":\"Gopal Varma\",
            \"salary\":\"500000\"
         },
         {
            \"id\":\"02\",
            \"name\":\"Sairamkrishna\",
            \"salary\":\"500000\"
         },
         {
            \"id\":\"03\",
            \"name\":\"Sathish kallakuri\",
            \"salary\":\"600000\"
         }
         ] 
      }";
      String data = "";
      try {
         JSONObject  jsonRootObject = new JSONObject(strJson);
         
         //Get the instance of JSONArray that contains JSONObjects
         JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
         
         //Iterate the jsonArray and print the info of JSONObjects
         for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            
            int id = Integer.parseInt(jsonObject.optString("id").toString());
            String name = jsonObject.optString("name").toString();
            float salary = Float.parseFloat(jsonObject.optString("salary").toString());
            
            data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
         }
         output.setText(data);
      } catch (JSONException e) {e.printStackTrace();}
   }
}
Following is the modified content of the xml res/layout/activity_main.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" 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=".MainActivity">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="JSON example"
      android:id="@+id/textView"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials Point"
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textSize="35dp"
      android:textColor="#ff16ff01" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="New Text"
      android:id="@+id/textView1"
      android:layout_below="@+id/textView2"
      android:layout_alignParentLeft="true"
      android:layout_alignParentStart="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentEnd="true" />
</RelativeLayout>
Following is the content of AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >
   
   <uses-permission android:name="android.permission.INTERNET"/>
   
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name=".MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      
   </application>
</manifest>
Let's try to run our application we just modified. I assume you had created yourAVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window:
Anroid XML Parser Tutorial
Above Example showing the data from string json,The data has contained employer details as well as salary information

Send Whatsapp Message via PHP Code

  How to Send and Receive Messages in WhatsApp using PHP In this tutorial you will see How to Send and Receive Messages in WhatsApp using PH...