How to display list of items with RecyclerView in Android.

When it's come to display list of items in android the best and ease way is to use RecyclerView.
RecyclerView is android widget which uses ViewHolder patter to save the inflated views,so that when user scroll the list then views are recycle and not created again.
Recycling of views is very use full from memory and performance perspective.


So,In this tutorial,
We gone a build simple example,we create MyRecyclerViewAdapter which extends from RecyclerView.Adapter class,this class is the adapter class which hold the data and view which we display in RecyclerView.
We need layout which represent list item,which we create in word_list_item.xml file.
We Also create activity_main.xml and MainActivity.Java to display Item List.

TrendyProgrammer's Code is well commented so you can find out what is going on in code,by just Reading it.

So Let's Look the Code:

MyRecyclerViewAdapter.Java
word_list_item.xml
MainActivity.Java
   activity_main.xml
Please Leave your Comments and Let Us Know Your Thoughts About This Tutorial. 

How to communicate between Android Activity and Fragment

In this fragment communication tutorial, We learn how to do communication between Android Activity and Fragment.
In this tutorial we create one fragment MyFragment which extends Fragment , in this fragment we create on Interface named FragmentInteractionListener this interface contain one method onRadioButtonSelected() , this method delegate choice made by user in Fragment to Activity.
Our MainActivity implements FragmentInteractionListener show when user make choice, we can get user choice in MainActivity.
In MainActivity we save user's choice and when you reopen fragment again then we can set user
previous choice.


Let's show the Code.


MainActivity.java
activity_main.xml
MyFragment.java.
fragment_layout.xml

Leave you comments And Let us know you thoughts about this tutorial.
-Trendy Programmer

How to Install WordPress in local computer

WordPress is CMS (content management system). Now day more than 80% website are running with WordPress.
WordPress is very easy to learn you can learn WordPress in couple of days.
We can create fully function website with WordPress withing 1 day.
In this tutorial we learn how to install WordPress in our local computer.

Step - 1
First download the latest version of WordPress from https://wordpress.org/download/
web site.


Step - 2 
Extract the downloaded .zip file and put extracted folder under the htdocs/ folder.
htdocs folder is created where you installed xampp server.(Mainly in your computer's c drive)

  
Step - 3
Now first start xampp server and go to any web browser and type localhost/demo
Note : don't forgot to replace demo folder name with your folder name where you putted extracted WordPress folder. 
Choose your desired language and press the Let's go button.


Step - 4
Now open the phpMyAdmin and create new DataBase.
Note: Save the database name to some where,because it will need in next step.


Step - 5
In this step enter the Database name which we just created in step - 4.
Enter the username this username is attached with you database,on localhost 
username is root.
You no need enter the password when you install wordpress on local computer.
Database Host will be localhost.
Table Prefix enter what type of table prefix you want in your data base.



Step - 6
Press the Run the installation button.


Step - 7
Now Enter the following fields as per you choose.
and check search engine visibility checkbox to true.
Site name - you site name
Username - username
password -  you desired password.
Your Email-  your email address.
Then press the Install WordPress button.



Step - 8
If Every thing is ok then you come up with success screen.
Press the LogIn button given in Success screen.
When you Press LogIn button you will redirected to login screen. 
Enter you Username and password in login screen press the login button.

Hurrah word is installed in you local computer.

 
Now WordPress is installed Press on visit site link given on wordpress deshborad. 
you can see the default WordPress site which come with wordpress setup.


 
Please leave you comment and let us know about your thoughts.

How to create fan control dial with android custom view.

Fan control dial example, In this example we create circular UI which represent physical fan dial control.



we use Custom view which extends from View class for draw a circular fan dial control and this custom view also draw text labels and indicator for settings fan speed.

0 means fan is off.
1 means fan is law.
2 means fan is medium.
3 means fan is high. 

When user click on fan dail then we move dial indicator to next position and we also change the fan dial color from Off to On when section is 1-3 for indicating that fan is turn on.  

Step -1       
First we create attribute file under the res/value folder this file is named attrs.xml.
In this attrs.xml file we create custom attribute for our custom fan dial view. 
attrs.xml 

Step - 2
In this step we create FanControlView class which extends View class, we will put all the logic inside this class.
 
FanControlView.java

  
Step - 3
In 3th Step we create activity_main.xml file under the res/layout.In activity_main.xml we use the 
FanControlView Class which we created in step-2. 

activity_main.xml

Step -4
In 4th Step we create MainActivity class which extends AppCompactActivity class,
This class is our main activity we uses activity_main.xml file to draw UI.

MainActivity.java
Please Leave your comment and let us know your thoughts.
So we can provide more useful tutorials.

How to create EditText view with clear Text Button

Custom EditText View


How to create custom Editing text view that includes "X" button for clearing entered text.

In this tutorial we are going learn how to make custome edit text view which containt "X" clear button and how to clear all the text from edit text view when "X" clear button is click.

I am extending EditText view class in my  CustomeEditTextWithClearButton class, so that we can get all basic functionality of EditText.

For the displaying "X" clear button image we are using
                           - SetCompoundDrawablesRelativeWithInstrinsicBounds();
of EditText view,we are setting setOnTouchListener with setOnTouchListener() method and find the touch event for the "X" button drawable for RTL and LTR Language and clear text from our CustumeEditTextView.

Let's Look at the code so we can get batter idea. 

CustomeEditTextWithClearButton.java 
How to Use  CustomeEditTextWithClearButton 

activity_main.xml
MainActivity.java


How to draw on android device screen with using your finger

Canvas Drawing Example


                                                          
  
In this example we are going to learn how to draw on device screen with custom view.

i am going to use canvas and bitmap for drawing you can use this technique when ever drawing on screen take less then 16 Milli seconds,which is frame update time on android.

In this example we are going to learn how to build custom android view, how to create bitmap, how to draw on canvas and how to handle motion events.

Not talking to much about theory let's have code.

Step-1
Create the java class which extends View class, this class will contain all the login for drawing.

 public class CanvasView extends View{}


Step-2
Define following Variables and objects and initialize them in class contractor

         private Paint paint                   - Will be use for drawing , it's like paint brash.
         private Path path;                    - We will draw with path like position A to position B.
         private int drawColor              - Color for drawing on the canvas.
         private int backgroundColor   - Background color of canvas.
         private Canvas extraCanvas    - Extra canvas for drawing.
         private Bitmap extraBitmap    - Extra Bitmap on which save the path.
         private Rect frame                   - Rectangle is for screen frame.

 

Initialize paint,drawColor,path,backgroundColor Variables in class contractor.

Like This:--

       CanvasView(Context context){
            this(context,null)
       }

       CanvasView(Context context,AttributeSet attributeSet){
             super(context)

             backgroundColor = ResourcesCompact.getColor(getResources(),R.color.green,null);

             drawColor = ResourceCompact.getColor(getResources(),R.color.yellow,null);

             //this will hold the path currently we are drawing.
             path = new Path();

             //Set the paint object,with which to draw.
             paint = new Paint();
             paint.setColor(drawColor);

             //Smoothes out edges of what is draw without affecting shape.
             paint.setAntiAlias(true);

             //Dithering affects how colors with higher-pricision
             //than the device are down-sampled.
             paint.setDither(true);

             paint.setStyle(Paint.Style.STROKE); // default is FILL
             paint.setStrokeJoin(Paint.Join.ROUND); // default is METER
             paint.setStrokeCap(Paint.Cap.ROUND); // default is BUTT
             paint.setStrokeWidth(12) // default is Heirline-width (realy thin)
      } 


Step-3
Initialize bitmap,canvas and rect varible in onSizeChanged() method.

onSizeChanged() method call when ever view's size is changed, so when view infilated and view   has  valid size at that time this method also call,so we are initialize bitmap and canvas and rect object in onSizeChanged method so that we have aqurate size of canvas,bitmap and rect for frame. 
so override onSizeChanged() methods as follow.


Like This:--

     /**
        *    onSizeChange called whenver the view changes size.
        *    Since the android view start with no size, this is also called after
        *    the view has been inflated and has a valid size.
        */
        @Override
        protected void onSizeChanged(int width,int height,
                                    int oldWidth,int oldHeight){
            super.onSizeChanged(width,height,oldwidth,oldHeight);

            //let's create the bitmap, create the canvas with bitmap, fill the canvas with color.
            extraBitmap = Bitmap.createBitmap(widht,height,Bitmap.Config.ARGB_8888);

            extraCanvas = new Canvas(extraBitmap);
            extraCanvas.drawColor(backgroundColor);


            //calculate the size of the rect , which will be the frame around the picture.
            int inset = 50;


            frame = new Rect(inset,inset,width - inset,height - inset);
        }

 

Step-4
Now override the onDraw() method and draw the bitmap and rect on canvas which passed as argument in onDraw() method.

override onDraw() method as follow.

Like This:--

      @Override
        protected void onDraw(Canvas canvas){
            //Draw the bitmap that has saved path
            canvas.drawBitmap(extraBitmap,0,0,null);

            //Draw the frame around the picture with rect.
            canvas.drawRect(frame,paint);

        }

 
Step-5  
In this step we are going to create two verible x and y which are the staring point for the path.
And also we are not draw for every single pixels,for that we are using  TOUCH_TOLERANCE
variable if finger moved greater than this distance then we are drawing on canvas else nothing we have to do.
We are creating 3 method which are used in drawing, i am creating this methods so that i can isolate the drawing code from motion event listener.


Like This:--

        // Variable for the new x,y values,
        //which are the staring point for the path
        private float x, y;

        // Don not draw every sigle pixel,
        // if the finger has moved less than this distance , don not draw
        private static final float TOUCH_TOLERANCE = 4;

        // The following methods feagure out what happens for different touch event,
        // as determined by the onTouchEvent() switch statement.
        // This keeps the swith statement
        // easier to change what happens for each event.

        
       
  private void touchIsStart(float x, float y){
            path.moveTo(x,y)
            this.x = x;
            this.y = y;
        }

        private void touchIsMove(float x , float y){
            float dx = Math.abs(x - this.x);
            float dy = Math.abc(y - this.y);

            if(dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE){
                // QuadTo() method of Path class adds a quadratic bezier from the last point,
                // approaching control point (x1,y1), and ending at (x2,y2)
                path.quadTo(this.x,this.y,(x + this.x)/2,(y + this.y)/2);

                this.x = x;
                this.y = y;

                // Draw the path in our extra bitmap to save it.
                extraCanvas.drawPath(path,paint);
            }

        private void touchIsUp(){
            //Reset the path so it is not draw again.
            path.reset();
        }   


  
Step-5  
Override the onTouchEvent() Method so that we can intercept  motion event which are fired when we touch the screen(view).
intentionally i have putted the invalidate() method inside the MotionEvent.ACTION_MOVE case because we not need to call invalidate() method for all the motion event,we are call the invalidate() method when ever we draw on canvas.

Like This:--

       @Override
        public boolean onTouchEvent(MotionEvent event){
            float x = event.getX();
            float y = event.getY();

            //I am puting Invalidate() method inside the case statements because there are many
            // other type of motion events passed into this listener,
            // and we do not want to invalidate the view for all those.

            swith(event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    touchIsStart(x,y);
                    //No need to call invalidate because we are not drawing anythig.
                break;

                case MotionEvent.ACTION_MOVE:
                    touchIsMove(x,y);
                    invalidate();
                break;

                case MotionEvent.ACTION_UP:
                    touchIsUp(x,y);
                break;
           
                defualt;

                    //do nothing
            }
           }


Step-6
We not need to create xml file for defining user interface. we can create CanvasView class object which we created above,and set it as content view of our activity as i do in following code.

Like This:--

/**
 *    CanvasDrawing example shows how to Build a custom view and draw on its canvas
 */
public class MainActivity extens AppCompactActivity{
   
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        CanvasView canvasView;

        // No need of xml file, just one custom view created programmatically.
        canvasView = CanvasView(this);

        //Request the full screen for layout.
        canvasView.setSystemUiVisibility(SYSTEM_UI_FLAG_FULLSCREEN);
        setContentView(canvasView);
    }


Full Code of Canvas drawing example

( 1 ) app/src/main/java/com/trenyprogrammer/canvasexample/CanvasView.java

package com.trendyprogrammer.canvasexample;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.support.v4.content.res.ResourcesCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.content.res.Resources;

/**
 * Custom view class which follow the touch events to draw on canvas.
 */

 public class CanvasView extends View{

         private Paint paint;
         private Path path;
         private int drawColor;
         private int backgroundColor;
         private Canvas extraCanvas;
         private Bitmap extraBitmap;
         private Rect frame;

         CanvasView(Context context){
             this(context,null)
         }

         CanvasView(Context context,AttributeSet attributeSet){
             super(context)

             backgroundColor = ResourcesCompact.getColor(getResources(),R.color.green,null);

             drawColor = ResourceCompact.getColor(getResources(),R.color.yellow,null);

             //this will hold the path currently we are drawing.
             path = new Path();

             //Set the paint object,with which to draw.
             paint = new Paint();
             paint.setColor(drawColor);

             //Smoothes out edges of what is draw without affecting shape.
             paint.setAntiAlias(true);

             //Dithering affects how colors with higher-pricision
             //than the device are down-sampled.
             paint.setDither(true);

             paint.setStyle(Paint.Style.STROKE); // default is FILL
             paint.setStrokeJoin(Paint.Join.ROUND); // default is METER
             paint.setStrokeCap(Paint.Cap.ROUND); // default is BUTT
             paint.setStrokeWidth(12) // default is Heirline-width (realy thin)
         }

        /**
        *    onSizeChange called whenver the view changes size.
        *    Since the android view start with no size, this is also called after
        *    the view has been inflated and has a valid size.
        */
        @Override
        protected void onSizeChanged(int width,int height,
                                    int oldWidth,int oldHeight){
            super.onSizeChanged(width,height,oldwidth,oldHeight);

            //let's create the bitmap, create the canvas with bitmap, fill the canvas with color.
            extraBitmap = Bitmap.createBitmap(widht,height,Bitmap.Config.ARGB_8888);
            extraCanvas = new Canvas(extraBitmap);
            extraCanvas.drawColor(backgroundColor);

            //calculate the size of the rect , which will be the frame around the picture.
            int inset = 50;

            frame = new Rect(inset,inset,width - inset,height - inset);
        }

        @Override
        protected void onDraw(Canvas canvas){
            //Draw the bitmap that has saved path
            canvas.drawBitmap(extraBitmap,0,0,null);

            //Draw the frame around the picture with rect.
            canvas.drawRect(frame,paint);
        }

        // Variable for the new x,y values,
        //which are the staring point for the path
        private float x, y;

        // Don not draw every sigle pixel,
        // if the finger has moved less than this distance , don not draw
        private static final float TOUCH_TOLERANCE = 4;

        // The following methods feagure out what happens for different touch event,
        // as determined by the onTouchEvent() switch statement.
        // This keeps the swith statement
        // easier to change what happens for each event.

        private void touchIsStart(float x, float y){
            path.moveTo(x,y)
            this.x = x;
            this.y = y;
        }

        private void touchIsMove(float x , float y){
            float dx = Math.abs(x - this.x);
            float dy = Math.abc(y - this.y);

            if(dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE){
                // QuadTo() method of Path class adds a quadratic bezier from the last point,
                // approaching control point (x1,y1), and ending at (x2,y2)
                path.quadTo(this.x,this.y,(x + this.x)/2,(y + this.y)/2);

                this.x = x;
                this.y = y;

                // Draw the path in our extra bitmap to save it.
                extraCanvas.drawPath(path,paint);
            }

        private void touchIsUp(){
            //Reset the path so it is not draw again.
            path.reset();
        }   

        @Override
        public boolean onTouchEvent(MotionEvent event){
            float x = event.getX();
            float y = event.getY();

            //I am puting Invalidate() method inside the case statements because there are many
            // other type of motion events passed into this listener,
            // and we do not want to invalidate the view for all those.

            swith(event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    touchIsStart(x,y);
                    //No need to call invalidate because we are not drawing anythig.
                break;

                case MotionEvent.ACTION_MOVE:
                    touchIsMove(x,y);
                    invalidate();
                break;

                case MotionEvent.ACTION_UP:
                    touchIsUp(x,y);
                break;
           
                defualt;

                    //do nothing
            }
           }

           //Get the width of the screen in pixel
           public static int getScreenWithInPixel(){
               return Resources.getSystem().getDisplayMetrics().widthPixels;
           }

           //Get the hight of the screen in pixel
           public static int getScreenHeightInPixel(){
               return Resources.getSystem().getDisplayMetrics().HeightPixels;
           }

}


( 2 ) app/scr/main/java/com/trendyprogrammer/canvasexample/MainActivity.java

package com.trendyprogrammer.canvasexample

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import static android.view.View.SYSTEM_UI_FLAG_FULLSCREEN;

/**
*    CanvasDrawing example shows how to Build a custom view and draw on its canvas
*/
public class MainActivity extens AppCompactActivity{
   
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        CanvasView canvasView;

        // No need of xml file, just one custom view created programmatically.
        canvasView = CanvasView(this);

        //Request the full screen for layout.
        canvasView.setSystemUiVisibility(SYSTEM_UI_FLAG_FULLSCREEN);
        setContentView(canvasView);
    }
}
 


Please leave your comments and let us know you opinion about this example.

you can download example code from here.






How to create android home screen widget with example


AppWidgetSample

Home widget is Representative of you application, all the home screen widget are listed in widget list and user can choose which ever widget they want to put on there home screen.

app widget provide user necessary information from your application, you can use app widget and increase user engagement with your application.

In Android development of app widget is very much easy, you can build fully function app widget with same line of code.

so, i am not going very much deep in theory, let's do same piratical.  

Pre-requesites
For this app you should be familiar with :
  1. Creating,building and ruining application in android studio.
  2. Sending and receiving broadcast intents.  
  3. Creating and sending pending intents.     

Image:-Widget list 
 Step-1
create new_app_widget_information.xml file under the app/src/main/res/xml/ directory of you project, this file contain all the meta data of the application widget which provide android os all the information necessary for app widget like app widget initial layout and app widget update cycle in milliseconds and other information


app/src/main/res/xml/new_app_widget_information.xml

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
    xmlns:android:="https://schemas.android.com/apk/res/android"
    android:initialKeyguardLayout="@layout/new_appwidget_layout"
    android:initialLayout="@layout/new_appwidget_layout"
    android:minHeight="185dp"
    android:minWidth="120dp"
    android:previewImage="@drawable/appwidget_preview"
    android:resizeMode="horizontal|vertical"
    android:updatePeriodMillis="1800000"
    android:widgetCategory="home_screen">
</appwidget-provider> 
  
 


step - 2
Now create the layout as you wish for your app widget.
This layout will display on home screen where the user will place the widget.

app/src/main/res/layout/new_app_widget.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:andorid="http://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#05C"
    android:padding="10dp">

    <LinearLayout>
        android:id="@+id/sectionId"
        style="@style/AppWidgetSection"
        android:layout_width="match_parent"
        android:layout_heigh="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:orientation="horizontal">


        <TextView
            android:id="@+id/appWidgetLabel"
            style="@style/AppWidgetLabel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="@string/widgetIdLabel"
            />
        <TextView
            android:id="@+id/appWidgetId"
            style="@style/AppWidgetText"
            android:layout_width="0dp"
            android:layout_height="wrep_contect"
            android:layout_weight="1"
            android:gravity="end"
            android:text="XX"
            />
    </LinearLayout>

    <!-- Panel for widget update date and number of updates -->
    <LinearLayout
        android:id="@+id/sectionUpdate"
        style="@style/AppWidgetSeciont"
        android:layout_width="match_parent"
        android:layout_height="wrap_contect"
        android:layout_align_parentLeft="true"
        android:layout_align_parentStart="true"
        android:layout_below="@id/sectionId"
        android:orientation="vertical">

        <TextView
            android:id="@+id/appWidgetUpdateLabel"
            style="@style/AppWidgetLabel"
            android:layout_width="match_parent"
            android:layout_height="wrap_contect"
            android:layout_marginBottom="2dp"
            android:text="@string/widgetUpdateLabel"
            />
        <TextView
            android:id="@+id/appWidgetUpdate"
            style="@style/AppWidgetText"
            android:layout_width="match_parent"
            android:layout_height="wrap_contect"
            android:text="@string/dateCountFormat"/>

        </LinearLayout>

        <!-- Button for udpate widget -->
        <Button
            android:id="@+id/buttonUpdate"
            style="@style/AppWidgetButton"
            android:layout_width="wrap_contect"
            android:layout_height="wrap_contect"
            android:layout_centerHorizontal="true"
            android:text="@string/updateWidgetBottom"
            />
    </RelativeLayout>

 

 Step - 3
Create the class which will extends AppWidgetProvider class from android framework, this class will be broadcast receiver which will receive all the update send by app widget when user interact with it.
You have to create RemoteViews class object from layout which we define above and after that you need to create pending intent and bind it with any desired view click event handler.

app/src/main/java/com/example/techbuffalos/appwidgetexample/NewAppWidget.java

package com.example.techbuffalos.appwidgetsample;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.RemoteViews;
import java.text.DateFormat;
import java.util.Date;

/*
* App widget provider class, to handle update broadcast intents and updates
* for the app widget
*/
public class NewAppWidget extends AppWidgetProvider{
   
    //Name of the shared preferances file.
    private static final String SHARE_PREF_FILE_NAME =    "com.example.techbuffalos.appwidgetsample";
    private static final String COUNT_KEY = "count";

/**
*    Update a single app widget.This is a helper method for the standard
*   onUpdate() callback that handles on widget update at a time.

*
*   @param context                 The application context.
*   @param appWidgetManager     The app widget manager.
*   @param appWidgetId          The current app widget id.
*
*/
private void updateAppWidget(Context context,
                            AppWidgetManager appWidgetManager,
                            int appWidgetId){

    // Retrive count from prefs.
    SharedPreferences prefsObj =
            context.getSharedPreferences(SHARE_PREF_FILE_NAME,0);

    int count = prefsObj.getInt(COUNT_KEY + appWidgetId,0);
    count++;

    //Get the current time
    String dateString=
        DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());

    RemoteViews view = new RemoteViews(context.getPackageName(),R.layout.new_app_widget.xml);

    views.setTextViewText(R.id.appWidgetId,String.valueOf(appWidgetId));
    views.setTextViewText(R.id.appWidgetUpdate,
            context.getResource().getString(
                R.string.data_count_format,count,dateString));   


    //save count back to prefs file
    SharedPreference.Editor prefEditor = prefObj.edit()
    prefEditor.putInt(COUNT_KEY + appWidgetId,count);
    prefEditor.apply();   

    //Setup update button to send update requrest as a pending intent
    Intent intentUpdate = new Intent(context,NewAppWidget.class);

    intentUpdate.setAction(AppWidgetManger.ACTION_APPWIDGET_UPDATE);

    // Include widget id to be update as intent extra
    int[] appWidId = new Int[]{appWidgetId};
    intentUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,appWidId);

    //wrap it all in intent to send a broadcast.
    //Use app widget id as request code (second argument) so that
    //each intent is unique.

    PendingIntent pendingIntent = PendingIntent.getBroadCast(context,
                appWidgetId,intentUpdate,PendingIntent.FLAG_UPDATE_CURRENT);

    //Assign pending intent to the button on click handler
    views.setOnClickPendingIntent(R.id.buttonUpdate,pendingIntent);


    //instract the app widget manager for update the widget.
    appWidgetManageer.updateAppWidget(appWidgetId,views);               
    }

    /**
    *    Override onUpdate method for handle all widget update request.
    *   
    *   @param context                 The application context.
    *   @param appWidgetManager     The app widget manager.
    *   @param appWidgetIds         An array of the app widget IDs.   
    */
    @Override
    public void onUpdate(Context context,AppWidgetManager appWidgetManager,int[] appWidgetIds){
   
        //There can be multiple widget active, so update all of them.
        for(int appWidgetId : appWidgetIds){
            updateAppWidget(context,appWidgetManager,appWidgetId)
        }
    }
}  


Step - 4 
Now one step to go, you need to register you AppWidgetProvider class to AndroidManifest.xml file as a BroadcastReceiver with android.appwidget.action.APPWIDGET_UPDATE intent action.
And also you must need to provide meta data with resource point to file which we create in step-1

app/src/main/AndoridManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.android.appwidgetsample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>

        <receiver android:name=".NewAppWidget">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/new_app_widget_information"/>
        </receiver>
    </application>
</manifest>

 
Bonus : 
Here is the style.xml file which contain all the style which i used in in this example.

app/src/main/res/values/styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resource>

<!-- Base application theme -->
<style name="AppTheme" parent="Theme.AppCompact.Light.DarkActionBar">
    <!-- Customize your theme here -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimartyDark</item>
    <item name="colorAccent">@color/colorAccent
</style>

<!-- style for widget's panle - linear layout with white backgournd -->
<style name="AppWidgetSection" parent="@android:style/widget">
   <item name="android:padding">8dp</item>
   <item name="android:layout_marginTop">12dp</item>
   <item name="android:layout_marginLeft">12dp</item>
   <item name="android:layout_marginRight">12dp</item>
   <item name="android:background">@android:color/white</item>
</style>

<!-- style for app widget for labels and main text -->
<style name="AppWidgetLabel" parent="AppWidgetText">
    <item name="android:textStyle">bold</item>
</style>

<!-- style for app widget button -->
<style name="AppWidgetButton" parent="Base.Widget.AppCompat.Button">
    <item name="android:layout_marginTop">12dp</item>
</style>

<style name="AppWidgetText" parent="Base.TextAppearance.AppCompat.Subhead">
    <item name="android:textColor">@android:color/black</item>
</style>
</resource>


Hope you all like this example,
Please leave you comments And let me know your thoughts about this post.

You can download all the code from here.