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

Android Application Concepts: The Activity

Android Application Concepts: The Activity


Android applications can be constructed from four different types of components: activities, services, broadcast receivers, and content providers. Of the four, the only one that you must use at least one of in every application (and the only one that I've had to use so far) is the activity.
I'm not going to even try to give a full explanation of what an activity is: the Application Fundamentals page on the Android Developers site provides a thorough (and rather long) explanation of activies as well as the other three components. So I'm just going to list some aspects of activities to give you a conceptual overview of what an activity is:
  • Each individual screen within an Android application is an activity, and users can perform actions by interacting with the visual components within an activity. Think of it as an individual web page within a modern web application, where the user can perform certain functions without leaving the page (using JavaScript), but must proceed to a different page in order to access a new set of tasks/functionality.
  • Each activity operates independently of one another (again, similar to how individual pages in a web application are separate from one another).
  • The visual objects within an activity (blocks of text, input boxes, buttons, etc.) are usually organized and instantiated by implementing instructions within a layout XML file.  They CAN be added individually with regular Java code, but the XML method is the recommended practice.
  • The transistion from one activity to another is accomplished through the use of asynchronous messages called Intents. An intent can be used to pass data from one activity to another, and that data is structured using key/value pairs. It's similar to how data is passed when an HTML form is submitted.
  • Each activity in an Android application is either a direct subclass of the Activity base class or a subclass of an Activity subclass that provides specialized functionality (such as the ListActivity class which contains methods specifically for the display of data in a touch-enabled list), and is represented in the application package as a single Java class.
  • All of the activities in the application must be defined in the application's manifest file, an XML file that keeps track of all of the components, resources, and permissions that make up the application.
  • All Android application components, including activities, have lifecycles. The current lifecycle state of a component provides part of the information the Android OS uses when it determines what components can be safely removed from memory in order to free up memory space. All activities inherit a set of lifecycle methods from the Activity base class that are executed when the corresponding lifecyle state of the activity is reached. These lifecycle methods are:
    • onCreate: the code within the onCreate lifecycle method is called when the activity is instantiated/loaded into memory. This is the method in which you want to set up the intial state of your variables, instantiate the visual objects within the activity via your layout file, and bind your event listeners. If you're a jQuery user, think of it as the equivalent of the document.ready function.
    • onStart: the method called when the activity becomes visible to the user.
    • onResume: the method called when the activity is moved to the foreground of the visible space, when the user is able to not only see the activity but interact with it. After the onResume method is called, the activity is considered to be "running."
    • onPause: called when the activity is no longer in the foreground, usually as the result of another activity being started.
    • onStop: called when the activity is no longer visible to the user in either the foreground or background.
    • onRestart: called when the activity is being restarted (made visible again) after executing onStop but not onDestroy.
    • onDestroy: called just before an activity is destroyed/unloaded from memory.

  • Any activity that isn't currently "running" could potentially be removed from memory by the Android OS if available system memory is low. The more inactive an activity is, the better the chance of it being destroyed to reclaim memory, so an activity that is "stopped" is in more danger of being removed from memory than an activity that is "paused."
  • Because even an activity that is "paused" can be destroyed under extremely low memory conditions, it is a best practice to run code to store/save any persistent data within the activity within the onPause method just in case (kind of like how the auto-save function works in Microsoft Office to save your work every few minutes).
  • To preserve the current state of an activity (like filtered search results) rather than persistent data, you can use code in the onSaveInstanceState method to perserve that data in a Bundleobject (which, like an intent, stores data in key/value pairs).  The onSaveInstanceState method in the activity is called by the Android OS itself as soon as the activity has the potential to be removed from memory. However, onSaveInstanceState is NOT called when the user explicitly takes action to destroy an activity (usually by exiting the entire application).
  • It is possible for one "application" to utilize activity objects from one or more different application packages (.apk files), given the proper planning and permissions.

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