Jul 25, 2014

Android Backgound Processing Service With Timer Task

This Example Show How To Use Services In Android With Timer Task.Our Main Task In This Example Is Start A Service and Run The Service In A Timer Task.Basically We Are Triggering The  Service In A Time Interval.A Service Is A Component That Runs In The Background To Perform Long-Running Operations Without Any Interact With The User.

First Of All We Need To Create A New Android Application Project.In My Case I'm Calling My Application As 'BackgroundService'.The Start up Window Appear As Below.





After Creating The Application We Have To Design Our Layout With Two Buttons.In My Case Im Calling My Buttons As 'Start Service' & 'End Service'.In Order To Do That Open The 'activity_main.xml' File.Replace The File With Following Codes.



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

   <Button android:id="@+id/btnStartService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/start_service"
    android:onClick="startService"/>

   <Button android:id="@+id/btnStopService"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/stop_service"
    android:onClick="stopService" />

</LinearLayout>


After Adding This Codes You Will Get Few Errors.Don't Worry About It.Errors Are Coming Because Because We Didn't Add The Strings to strings.xml File.In Order To Do That Go To res --> values --> strings.xml And Add The Two Strings As Follows.


<resources>
    <string name="app_name">HelloWorld</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">MainActivity</string>
    <string name="start_service">Start Service</string>
    <string name="stop_service">Stop Service</string>
</resources>



Now We Have Our Layout and We Need To Create Service Class.In Order To Create Service Class Right Click The 'src' Folder & Go To New --> Class.It Will Open You A New Window To Create A New Class.Give The Class Name,Make The Class As Public Too.In My Case I'm Calling My Service Class As 'MyService'. 


package com.example.backgroundprocess;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

   private static Timer timer = new Timer();
   private Context ctx;

   @Override
   public IBinder onBind(Intent arg0) {
      return null;
   }

   public void onCreate() {
      super.onCreate();
      ctx = this; 
      startService();
   }

   private void startService(){           
      timer.scheduleAtFixedRate(new mainTask(), 0, 5000);
   }

   private class mainTask extends TimerTask
      public void run(){
         toastHandler.sendEmptyMessage(0);
      }
   }

   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this,"Service Distroyed",Toast.LENGTH_SHORT).show();
   }

   private final Handler toastHandler = new Handler(){
      @Override
      public void handleMessage(Message msg){
         Toast.makeText(getApplicationContext(),"Service Started",Toast.LENGTH_SHORT).show();
      }
   };

}


Now We Have To Call This Service To Start.In Order To Do That We Have To Add Few Code Lines To 'MainActivity.java'.


package com.example.backgroundprocess;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // Method to start the service
    public void startService(View view) {
       startService(new Intent(getBaseContext(), MyService.class));
    }

    // Method to stop the service
    public void stopService(View view) {
       stopService(new Intent(getBaseContext(), MyService.class));
    }
}

Change Manifest To Identify The Service.Add Following Code In AndroidManifest File In Between "</activity>" &  "</application>" Tags As Follows.


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

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="9" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.backgroundprocess.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>
        <service android:name=".MyService" />
    </application>

</manifest>


Now We Have Completed Our Coding Parts.Now Run The Application & See.After Clicking 'Start Service' You Will Get The Out Put As Below.


Every 5 Seconds You Will Get This Toast.Now Press The 'Stop Service' Button.You Will Get The Following Output.


Now You Can Use This Is Simple Application As A Component To Your Application. 
For Your Knowledge : You Can Start A Services Many Time Without Even Stopping It.But You Can Only Stop A Service If Their Is A Running Service Only.
 


Jul 24, 2014

Card , Deck , Hand Class In Poker Game Using Java

This Tutorial Is Focused On Initial Development Of  A Poker Game Using Java. Initially You Need Three Java Classes.Which Need To Store Card Details, Card Deck Details and Player Hand Details.

1. Card Class

This Class Contain The Information About A Card.Such As Card Index Which Vary From 1-52(Altogether Their Are 52 Playing Cards In The Pack), Card Suit Which Vary From 1-4(Their Are Four Suits In The Card Pack) and Card Value Which Vary From 2-14.

Also This Class Contain Few Methods To Get The Card Index , Card Suit and Card Value.This Class Should Have A Method To Create A New Card.In This Example I Have Used The Parameter Constructor To Create A New Card Objects. 


public class Card{

   private int CardIndex;//Vary From 0 to 51
   private int CardSuit;//Vary From 1 to 4 ( 1=Spades, 2=Hearts, 3=Clubs, 4=Diamonds)
   private int CardValue;//Vary From 2 to 14 ( 11=Jack, 12=Queen, 13=King, 14=Ace)

   public Card(){
   }

   public Card(int CardIndex,int CardSuit,int CardValue){
      this.CardIndex = CardIndex;
      this.CardSuit  = CardSuit;
      this.CardValue = CardValue;
   }

   public int getCardIndex(){
      return CardIndex;
   }

   public int getCardSuit(){
      return CardSuit;
   }

   public int getCardValue(){
      return CardValue;
   }

}

2.Deck Class

This Class Contains Set Of Card Objects.Initially This Class Contains All The 52 Card Objects.In A Game This Class Contains Current Card Objects Available In The Deck.To Store The Card Objects This Class Has An Array List Of Card Type.

Initially When The Game Is Starting, Deck Class Should Have All The 52 Card Objects. In This Class We Are Using Default Constructor To Create The Deck With 52 Card Objects.

Also This Class Should Have Few Methods To Shuffle The Deck , Get The Deck Size , Deal A Card From Deck and Add A Card To Deck.

import java.util.ArrayList;
import java.util.Collections;

public class Deck {

   private ArrayList<Card> deck = new ArrayList<Card>();//Cards Available In The Deck

       //Creating The Card Pack
   public Deck() { 
      int iIndex = 1;
      for (int iSuit = 1; iSuit < 5; iSuit++) { // 1=Spades, 2=Hearts, 3=Clubs, 4=Diamonds
         for(int iValue = 2; iValue < 15; iValue++ ) { //11=Jack, 12=Queen, 13=King, 14=Ace
            deck.add(new Card(iIndex,iSuit,iValue));
            iIndex++;
         }
      }
   }

   //Shuffles The Deck
   public void shuffle() {
      Collections.shuffle(deck);
   }

   //Get The Deck Size
   public int getDeckSize() {
      return deck.size();
   }

   //Deals(Return & Remove) A Card From The Top Of The Deck
   public Card dealCard() {
      return (Card)deck.remove(0);
   }

   public void addCard(Card c){
      deck.add(c);
   }

}

3.Hand Class

This Class Contains Set Of Card Objects Which Player Has.Initially This Class Has No Card Objects.In A Game This Class Contains Current Card Objects Available In The Player Hand.This Class Has An Array List Of Card Type To Store The Card Objects That Are Available In The Player Hand .

Also This Class Should Have Few Methods To Get The Hand Size ,  Add A Card To Hand, Get A Card From Hand and To Return The Hand Card List.

import java.util.ArrayList;

public class Hand {

   private ArrayList<Card> hand = new ArrayList<Card>();//Cards Available In The Hand

   public Hand(){
   }

   //Used To Add A Card To Hand
   public void addCard(Card c) {
      hand.add(c);
   }

   //Used To Remove A Card From Hand
   public Card removeCard(int iCardIndex) {
      Card x = new Card();
      for (Card c : hand) {
         if (c.getCardIndex() == iCardIndex) {
            x = c;
         }
      }
      hand.remove(x);
      return x;
   }

   //Used To Get The HandSize
   public int getHandSize() {
      return hand.size();
   }

   //Used To Get The CardList
   public ArrayList<Card> getHandCard() {
      return hand;
   }

}
   



Jul 18, 2014

Break and Continue Keyword In Java

Break Keyword

"Break" Key Word Is Used For Stop The Entire Loop. The Break Keyword Must Be Used Inside A Loop Or In A Switch Statement.The Break Keyword Will Stop The Execution Of The Innermost Loop & It Will Move Outside The Loop To Execute The Rest Of The Codes.   

Syntax Is Simply "break;" Inside The Loop.

Following Example Shows How To Use Break Keyword Inside A Loop.

class EasyCodeStuff {
   public static void main(String args[]){

      int [] MyNumbers = {5,3,8,2,6,1,11};

      for(int MyCount : MyNumbers){
         if(MyCount == 6){
            break;
         }
         System.out.print("My Count Is : ");
         System.out.println(MyCount); 
      }
   }


OutPut

My Count Is : 5
My Count Is : 3
My Count Is : 8
My Count Is : 2  
  
In The Above Example Inside The For Loop We Have If Condition To Check "MyCount" Variable Value. If "MyCount" Variable Value Is 6, It Will Exit The Loop.



Continue Keyword

The "Continue" Keyword Can Be Used In Any Of The Loop Control Structures. It Causes The Loop To Immediately Jump To The Next Iteration Of The Loop.The Continue Statement Is Used To Jump To The Next Iteration Of A For Or While Loop, By Skipping The Rest Of The Code Lines In The Current Iteration.

The Different Between Continue and Break Statement Is If We Use Break Inside A For Loop It Will Exit From The For Loop.But If We Used A Continue Statement Inside For Loop It Will Go To The Update Statement Of The For Loop. 

If We Used  "continue;" Keyword Inside A While Loop Or Do While Loop It Move To The Boolean Expression Of The Loop.

Syntax Is Simply "continue;" Inside The Loop.
Following Example Shows How To Use Continue Keyword Inside A Loop.

class EasyCodeStuff {
   public static void main(String args[]){

      int [] MyNumbers = {5,3,8,2,6,1,11};

      for(int MyCount : MyNumbers){
         if(MyCount == 6){
            continue;
         }
         System.out.print("My Count Is : ");
         System.out.println(MyCount); 
      }
   }


OutPut

My Count Is : 5
My Count Is : 3
My Count Is : 8
My Count Is : 2My Count Is : 1
My Count Is : 11



For Loop and Enhanced For Loop In Java

For Loop

For Loop Allows Code To Be Repeatedly Executed. A For Loop Is Classified As An Iteration Statement. A For Loop Can Be Use, When We Know How Many Times A Code Is To Be Repeated. For Loop Syntax Looks Like Below.

for(initialization; Boolean_expression; update)
{
   //Code We Want To Run Repeatedly 
}


Inside The Brackets Of The For
 Loop You Have To Define A Variable & Initialized It To A Value.Then Put A Semi Colon & Write The Boolean Condition To Run The For Loop. After That Put Another Semi Colon & Write The Update Statement For The For Condition Variable.

Following Example Shows How To Use While Loop In Java.

class EasyCodeStuff {
   public static void main(String args[]){

      for(int MyCount = 1; MyCount < 5; MyCount++){
         System.out.print("My Count Is : ");
         System.out.println(MyCount);
      }
   }


OutPut

My Count Is : 1
My Count Is : 2
My Count Is : 3
My Count Is :
 

Enhanced For Loop 

Enhanced For Loops Also Like For Loop. Enhanced For Loops Mainly Used With Arrays. Enhanced For Loop Syntax Looks Like Below.


for(declaration : expression)
{
   //Code We Want To Run Repeatedly  
}

In Enhanced For Loops Declared Variable Type Must Be Compatible With The Array That We Are Going To Use In The Enhanced For Loop.For Example If We Have A Integer Array We Have To Use The Declaration Variable As Integer Too. In The Expression You Have To Give The Array. 
Following Example Shows How To Use While Loop In Java.

class EasyCodeStuff {
   public static void main(String args[]){

               int [] MyNumbers = {1,2,3,4,5};
      for(int MyCount : MyNumbers){
         System.out.print("My Count Is : ");
         System.out.println(MyCount); 
      }
   }


OutPut

My Count Is : 1
My Count Is : 2
My Count Is : 3
My Count Is : 4  
My Count Is : 5  

While and Do While Loop In Java

While Loop

While Loop Is A Control Flow Statement That Allows Code To Be Executed Repeatedly Based On A Given Boolean Condition. The While Loop Can Be Thought Of As A Repeating If Statement.While Loop Syntax Looks Like Below.
 
while ( condition ) {
     //Codes You Want To Execute After Condition Is True

}

We Have To Write "while" In Lowercase.The Condition We Want To Write Goes Inside The Round Brackets. We Can Write The Code That We Want To Execute Inside The Curly Brackets.Make Sure You Have Change The Condition Varible Value In Side The Curly Brackets.Otherwise You Will End Up With A Infinite Loop.

Following Example Shows How To Use While Loop In Java.

class EasyCodeStuff {
   public static void main(String args[]){

      int MyCount = 1;
       
      while(MyCount < 5){
         System.out.print("My Count Is : ");
         System.out.println(MyCount);
         MyCount++; 
      }
   }


OutPut

My Count Is : 1
My Count Is : 2
My Count Is : 3
My Count Is : 4  


Do While Loop

Do While Loop Is Related To While Loop.The Main Difference Between While Loop and Do While Is, In Do While Loop, Loop Will Run At Least Once, Even Without Condition Is False.In Do While Loop, While Is In Bottom and Do Is At The Top.We Have To Write The Codes That We Want To Execute Inside The Curly Brackets That Are With The Do Loop.Do While Loop Syntax Looks Like Below.


do{
     //Codes You Want To Execute After Condition Is True

}
 while ( condition ); 


Following Example Shows How To Use Do While Loop In Java.

class EasyCodeStuff {
   public static void main(String args[]){

      int MyCount = 1;
      
      do{
         System.out.print("My Count Is : ");
         System.out.println(MyCount);
         MyCount++; 
      }
      while(MyCount < 5)
   }


OutPut

My Count Is : 1
My Count Is : 2
My Count Is : 3
My Count Is : 4


Jul 17, 2014

Switch Statement in Java

We Can Use Switch Statement for Do Many Different Things Depending On One Variable. For Example You May Have Variable Called Month To Store The Month From 1 to 12. Depending On The Month You can Do Multiple Things.

Following Example Demonstrate How To Use Switch Statement.

class EasyCodeStuff {
   public static void main(String args[]){
      
      int MyMonth = 2;

      switch(MyMonth){

      case 1:
         System.out.print("January");
         break;
      case 2:
         System.out.print("February");
         break;
      case 3:
         System.out.print("March");
         break;
               case 4:
         System.out.print("April");
         break;
      case 5:
         System.out.print("May");
         break;
      case 6:
         System.out.print("June");
         break;
      case 7:
         System.out.print("July");
         break;
      case 8:
         System.out.print("August");
         break;
      case 9:
         System.out.print("September");
         break;
      case 10:
         System.out.print("October");
         break;
      case 11:
         System.out.print("November");
         break;
      case 12:
         System.out.print("December");
         break;
      default:
         System.out.print("Invalid Month");
         break;
      }
   }
}

Above Example Will Give The Out Put As "February".Because The Value Of The "MyMonth" Variable Is 2.

"case 1" Mean , Value Of "MyMonth" Variable Is 1. After The Colon(:) You Can Write Your Codes, What You Want To Do After "MyMonth" Variable Have Value 1.But Make Sure You Have Put A "break;" Statement In Last Line.

In The Following Example You Can See Their Statement Called "default;" After The Last Case Statement. This Section Execute If Non Of The Case Are Not True. 


Java Logical Operators ( And && Or || )

If You Have To Check Two Variable Values To Given  Two Values, You May Some Time Write Many If Else Statements To Check For Many Variable Values.Without Writing Many If Else Statement You Can Check Many Values That Mean Many If Else Statements In A Single Statement By Using AND or OR Logical Operators.  

You Can Use AND(&&) Logical Operator If You Want To Do Something After Every Operator Gets True.

You Can Use OR(||) Logical Operator If You Want To Do Something After Any Of The Operator Gets True.

Following Example Demonstrate How AND , OR Operators Work.

class EasyCodeStuff {
   public static void main(String args[]){
     
      int No1 = 10;
      int No2 = 20;

      //AND Logical Opearator

      if (No1 == 10 && No1 == 20){
         System.out.println("No1 is Equal To 10 AND No2 is Equal To 20");
      }else{
         System.out.print("No1 is Not Equal To 10 OR No2 is Not Equal To 20");
      }
      
      //OR Logical Operator
      if (No1 == 10 || No1 == 20){
         System.out.println("No1 is Equal To 10 OR No2 is Equal To 20");
      }else{
         System.out.print("No1 is Not Equal To 10 AND No2 is Not Equal To 20");
      }
   }
}    



JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...