Sunday, 31 March 2013

The role of Transformation Matrices in Animation

The mechanics of animation of are quite simple. Take any scene and if you repaint it quick while some aspect of that scene is changing you get the impression that something is moving smoothly although the repaint is happening only with a certain frequency which is typically 24 or 12 frames per second.
what changes at every redraw may be color, position, orientation, or size or any combination of these. If you want to take a view or a scene or a picture and want to move that scene to the right by a few pixels, you will typically define a transformation matrix and then apply a matrix multiplication or transformation on every pixel of the scene to get the new location. So each tranformation is identified by a certain matrix.
If you start with an identity matrix and then apply each transformation to it then you will get a final matrix that you can apply just one time to transform the view. By changing these matrices in a gradual manner in a time loop you will accomplish animation. Let's spend a little bit more time and understand the matrix api before going further.
You can get an identity matrix by doing

Matrix matrix = new Matrix();
To achieve rotation you can do

This method will rotate the view around origin by those many degrees in a 2D space. Some other methods are

As you call these methods to arrive at a desired matrix be aware of the "set" semantics. "set" semantics works like a "setting" a variable which means "replace" the current value with the new value. All of these methods, if you follow the java source code of android eventually resolve to some c++ code from a core google graphics library called "skia". You can explore the source code online at
"git" is a source code control system used by the android open source project. You can learn more about "git" SCM here at
Now back to understanding of the "set" semantics on these graphics matrices. Let us take a look at the source code for "setScale":

void SkMatrix::setScale(SkScalar sx, SkScalar sy) {
    fMat[kMScaleX] = sx;
    fMat[kMScaleY] = sy;
    fMat[kMPersp2] = kMatrix22Elem;

    fMat[kMTransX] = fMat[kMTransY] =
    fMat[kMSkewX]  = fMat[kMSkewY] = 
    fMat[kMPersp0] = fMat[kMPersp1] = 0;

    this->setTypeMask(kScale_Mask | kRectStaysRect_Mask);
The scale function replaces all previous scaling values and pretty much resets the matrix and sets the scale. So if you have done anything else to the matrix all that is gone. Let us take a look at the "setTranslate" to see if that is any different.

void SkMatrix::setTranslate(SkScalar dx, SkScalar dy) {
    if (SkScalarAs2sCompliment(dx) | SkScalarAs2sCompliment(dy)) {
        fMat[kMTransX] = dx;
        fMat[kMTransY] = dy;

        fMat[kMScaleX] = fMat[kMScaleY] = SK_Scalar1;
        fMat[kMSkewX]  = fMat[kMSkewY] = 
        fMat[kMPersp0] = fMat[kMPersp1] = 0;
        fMat[kMPersp2] = kMatrix22Elem;

        this->setTypeMask(kTranslate_Mask | kRectStaysRect_Mask);
    } else {
Basically sets the scale back to 1 and sets the translations replacing everything before.
So what do you do if you want to apply multiple transformations in a tow. Matrix class provides a set of "pre*" and "post*" functions for each of the "set*" fucnctions. Let us take a look at the source code for "preScale"

bool SkMatrix::preScale(SkScalar sx, SkScalar sy, SkScalar px, SkScalar py) {
    SkMatrix    m;
    m.setScale(sx, sy, px, py);
    return this->preConcat(m);

bool SkMatrix::preConcat(const SkMatrix& mat) {
    return this->setConcat(*this, mat);

bool SkMatrix::postConcat(const SkMatrix& mat) {
    return this->setConcat(mat, *this);
Essentially "preScale" creates a brand new matrix with the given scale and then multiplies that matrix with the current matrix and replaces the current matrix with the resultant matrix. When matrices are multiplied the order is important. So if we do

m.setScale(..) = rm1
m.preScale(..) = m2 x rm1 = rm3
m.postScale(..) = rm3 x m4 = rm5
I could have acheived the same with

m1.setScale() = m1
m2.setScale() = m2
m3.setScale() = m3

m1.setConcat(m2,m1); // rm3
m1.setConcat(m1,m3); // rm5
You can concat
If "m1" was an identity matrix then the following two would be equal as well

m1.postTranslate(); // take it to the origin
m1.postScale(); //scale it
m1.postTranslate();// take it back to the center


Here is some more sample code demonstrating matrix equivalence based on the order of operations on that matrix

In summary all the "pre*" and "post*" methods are mere shortcuts to "setConcat" against itself.

preTranslate(m) -> setConcat(m x self) 
preRotate(m) -> setConcat(m x self)
preScale(m) -> setConcat(m x self)
preSkew(m) -> setConcat(m x self)

postTranslate(m) -> setConcat (self x m)
postRotate(m) -> setConcat (self x m)
postScale(m) -> setConcat (self x m)
postSkew(m) -> setConcat (self x m)

Introduction To Animation In Android

Android supports two kinds of animation. 
  • One is called "Tweened Animation". 
  • The second one is called "Frame by Frame" animation. 
"Tween" is a short for "in-between" borrowed from traditional animators. Inbetweens are drawings that simulate motion between key frames. There may be 24 inbetweens between two key frames or there could be 12 between two key frames. The former case is called "on ones" and the later ones are called "on twos".

In Android here is how "tweening" works. You start with a view. This view can be any view including a view group with any set of complex composed graphical objects. When tweening animation is attached to this view, the animation gets a call back at regular intervals to change any aspect of the tranformation matrix that would be used to render the view.

Moving an object or scaling an object, or changing the shade of an object can all be represented as a set of matrix transformations. By changing this matrix in the call back of the animation you will render the object at a different place with a different scale or a diferent color.

So at a general level, tweening animation is acomplished by changing the properties of a view at various time intervals during the alloted time of an animation.

Android supports the following types of "tween" animations

  • AlphaAnimation: Changing Transparency of an object
  • RotateAnimation: Rotating an object
  • ScaleAnimation: Scale an object
  • TranslateAnimation: Move an object

In Android frame by frame animation a series of drawable resources are loaded one after the other. The class AnimationDrawable is responsible for frame by frame animation. Each frame in this animation is a drawable resource.

As you get deeper into Android animation you will see that the distinction is not so clearcut where you can mix both concepts by essentially redrawing the canvas one way or the other.

Monday, 11 March 2013

Android Distance Direction With Google Map (JSON)


NOTE: Check  your Android Manifest..

My Layout.xml

1) Create class MyOverLay which extends Overlay

2) Create another class CustomItemizedOverlay which extends ItemizedOverlay<OverlayItem>


3) Now Create Main Activity which extends MapActivity

OCWCD Chapter 2 : Web App architecture

A container runs and controls the servlets.
A full J2EE application server must have both a web container and an EJB container.
When a request is received by the webserver and needs to access a servlet, the webserver hands the
request to the servlet-helper app : the container. Then the container hands the request to the servlet

  •  Match the request URL to a specific servlet;
  • Creates request and response objects used to get informations from the client and send back informations to him;
  • Creates the thread for the servlet;
  • Calls the servlet’s service() method, passing request and response objects as parameters;
  • service() method will call the doXxx() method of the servlet depending on request type;
  •  Get the response object from the finished service() method and converts it to an HTTP response;
  •  Destroys request and response objects;
  •  Sends back response to the webserver

Capabilities of containers

Containers provide :
  • Communications support : handles communication between the servlets and the webserver
  • Lifecycle management : controls life and death of servlets, class loading, instantiation, initialization, invocation the servlets’ methods, and making servlet instances eligible for GC
  • Multithreading support : Automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies.
  • Declarative security : manages the security inside the XML deployment descriptor file. Security can be configured and changed only by modifying this file.
  • JSP support : Manages the JSPs.
URL to servlet mapping

The servlet container uses the deployment descriptor to map URL to servlets. Two DD elements
are used to achieve this :

<servlet> : maps internal name to fully qualified class name;
<servlet-mapping> : maps internal name to public URL name.

Model-View-Controller (MVC) Design

MVC does not only separates the Business Logic from the presentation, the Business Logic doesn’t
even know there is a presentation.
MVC : separate Business Logic (model) and the presentation, then put something between them toconnect them (controler), so the business can become a real re-usable code, and the presentation layer can be modified/changed at will.


Overview :

  • HTTP stands for HyperText Transport Protocol, and is the network protocol used over the web. It runs over TCP/IP.
  • HTTP uses a request/response model. Client sends an HTTP request, then the server gives back the HTTP response that the browser will display (depending on the content type of the answer) If the response is an HTML file, then the HTML file is added to the HTTP response body
  • An HTTP response includes : status code, the content-type (MIME type), and actuel content of the response
  • A MIME type tells the browser what kind of data the response is holding URL stands for Uniform Resource Locator: starts with a protocol, then a server name, optionnaly followed by a port number, then the path to the resource followed by the resource name. Parameters may appear at the end, separated from the rest by a ?

HTTP methods

GET Gets the data identified by an URI
POST Same, the request’s body is passed to the resource specified by the URI
HEAD Sends back only the header of the response that would be sent by a GET
PUT Sends to the server data to store at specified URI. Server does not process the
data ; it only stores them
DELETE Delete specified resource
TRACE When it receives this request, the server sends it back to the client
OPTIONS Ask server informations about a resource or about its own capabilities
CONNECT Ask for a connction (tunnelling)

Differences between GET and POST

POST has a body.
GET parameters are passed on the URL line, after a ?. The URL size is limited.
The parameters appear in the browser URL field, hence showing any password to the world...
GET is supposed to be used to GET things (only retrieval, no modification on the server).
GET processing must be idempotent.

A click on a hyperlink always sends a GET request.
GET is the default method used by HTML forms. Use the method=”POST” to change it.

In POST requests, the parameters are passed in the body of the request, after the header. There is no
size-limit. Parameters are not visible from the user.
POST is supposed to be used to send data to be processed.
POST may not be idempotent and is the only one.

IDEMPOTENT : Can do the same thing over and over again, with no negative side effect.

10 Fantastic Ideas for B2B Mobile Apps

1.) Supply Ordering App: Are you a business product supplier? Create a supply ordering app that lets people order new supplies by photographing a bar code on the product they need restocked. Users can securely store their shipping and billing information in the app, edit the quantity, and quickly get more of the supplies they need. Make their lives even easier by tapping into their buying history and providing push notifications for when they are likely running low on a certain supply. You should also include reviews, recommended products, and shipping status notifications for a superior experience.

2.) Event App: Plan on hosting an event this year? Create an event-specific app with exhibit maps, session schedules, speaker bios, and attendee-provided contact information for networking. You can also let people push out messages to Twitter, LinkedIn, and Facebook right from the app.

3.) ROI Calculator: The ROI calculator is a tried and true app for business people who are constantly on the hook for proving ROI. Whatever action you want your prospects to take, an app that lets them quickly calculate the ROI of some aspect of it not only makes them happier, but it also makes your sale easier.

4.) Code Generator: Have an audience that has to do online design during their day job? Create a code generator to make it easier! For example, a marketer who is a novice with HTML might select your HTML code generator to quickly figure out how to code her next email campaign. That's one helpful app that can be used over and over, and spread to a wider audience quickly.

5.) Security Alert App: Are your customers concerned with online security? People in IT security or software can create an app that delivers security alerts when customers experience a security breach. IT departments the world over will love you for it.

6.) Networking App: Use the location-aware capabilities of mobile devices to create an app that lets your prospects and customers find people in their industry with which to network. Couple this with thought leadership content delivered through your app, and you're on your way to becoming the LinkedIn of your industry.

7.) Content Segmenting App: Is your content one of your biggest assets? If you're publishing high volumes of content, create an app that lets your readers select only the topics they want to learn about, and receive updates when you publish something new on that subject.

8.) Software Features App: If you're a software company, make an app that lets people use features of your software on their mobile devices. For example, create an app that alerts your sales team when a new lead needs to be contacted. This way, they can beat your competitors to the punch and make sales even when they're not at their desk!

9.) Calculator App: B2B companies with an audience in a mathematical field can create a calculator app. Provide quick calculations based on frequently used formulas to help them out in their day-to-day job. This will solidify your status as a reliable and helpful resource in your industry and make you a part of their daily lives.

Basic Syntax And First Java Program

First Java Program:

Let us look at a simple code that would print the words Hello World.
public class MyFirstJavaProgram {

   /* This is my first java program.  
    * This will print 'Hello World' as the output

    public static void main(String []args) {
       System.out.println("Hello World"); // prints Hello World
Lets look at how to save the file, compile and run the program. Please follow the steps given below:
  • Open notepad and add the code as above.
  • Save the file as :
  • Open a command prompt window and go o the directory where you saved the class. Assume its C:\.
  • Type ' javac ' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line.( Assumption : The path variable is set).
  • Now type ' java MyFirstJavaProgram ' to run your program.

  • You will be able to see ' Hello World ' printed on the window.

  • >
    C : > javac
    C : > java MyFirstJavaProgram 
    Hello World

    Basic Syntax:

    About Java programs, it is very important to keep in mind the following points.
    • Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have different meaning in Java.
    • Class Names - For all class names the first letter should be in Upper Case.

      If several words are used to form a name of the class each inner words first letter should be in Upper Case.

      Example class MyFirstJavaClass
    • Method Names - All method names should start with a Lower Case letter.

      If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.

      Example public void myMethodName()
    • Program File Name - Name of the program file should exactly match the class name.

      When saving the file you should save it using the class name (Remember java is case sensitive) and append '.java' to the end of the name. (if the file name and the class name do not match your program will not compile).

      Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as''
    • public static void main(String args[]) - java program processing starts from the main() method which is a mandatory part of every java program..

    Java Identifiers:

    All java components require names. Names used for classes, variables and methods are called identifiers.
    In java there are several points to remember about identifiers. They are as follows:
    • All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an underscore (-).
    • After the first character identifiers can have any combination of characters.
    • A key word cannot be used as an identifier.
    • Most importantly identifiers are case sensitive.
    • Examples of legal identifiers:age, $salary, _value, __1_value
    • Examples of illegal identifiers : 123abc, -salary

    Java Modifiers:

    Like other languages it is possible to modify classes, methods etc by using modifiers. There are two categories of modifiers.
    • Access Modifiers : defualt, public , protected, private
    • Non-access Modifiers : final, abstract, strictfp
    We will be looking into more details about modifiers in the next section.

    Java Variables:

    We would see following type of variables in Java:
    • Local Variables
    • Class Variables (Static Variables)
    • Instance Variables (Non static variables)

    Java Arrays:

    Arrays are objects that store multiple variables of the same type. However an Array itself is an object on the heap. We will look into how to declare, construct and initialize in the upcoming chapters.

    Java Enums:

    Enums were introduced in java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.
    With the use of enums it is possible to reduce the number of bugs in your code.
    For example if we consider an application for a fresh juice shop it would be possible to restrict the glass size to small, medium and Large. This would make sure that it would not allow anyone to order any size other than the small, medium or large.


    class FreshJuice {
       enum FreshJuiceSize{ SMALL, MEDUIM, LARGE }
       FreshJuiceSize size;
    public class FreshJuiceTest {
       public static void main(String args[]){
          FreshJuice juice = new FreshJuice();
          juice.size = FreshJuice. FreshJuiceSize.MEDUIM ;
    Note: enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.

    Java Keywords:

    The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.

    Comments in Java

    Java supports single line and multi-line comments very similar to c and c++. All characters available inside any comment are ignored by Java compiler.
    public class MyFirstJavaProgram{
       /* This is my first java program.
        * This will print 'Hello World' as the output
        * This is an example of multi-line comments.
        public static void main(String []args){
           // This is an example of single line comment
           /* This is also an example of single line comment. */
           System.out.println("Hello World"); 

    Using Blank Lines:

    A line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally ignores it.


    In java classes can be derived from classes. Basically if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.
    This concept allows you to reuse the fields and methods of the existing class with out having to rewrite the code in a new class. In this scenario the existing class is called the super class and the derived class is called the subclass.


    In Java language an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance.
    An interface defines the methods, a deriving class(subclass) should use. But the implementation of the methods is totally up to the subclass.

    Features of JAVA

    Hello, Welcome Here ...

    1) Compiled and Interpreter:- has both Compiled and Interpreter Feature Program of java is First Compiled and Then it is must to Interpret it .First of all The Program of java is Compiled then after Compilation it creates Bytes Codes rather than Machine Language. Then After Bytes Codes are Converted into the Machine Language is Converted into the Machine Language with the help of the Interpreter So For Executing the java Program First of all it is necessary to Compile it then it must be Interpreter

    2) Platform Independent:- Java Language is Platform Independent means program of java is Easily transferable because after Compilation of java program bytes code will be created then we have to just transfer the Code of Byte Code to another Computer. This is not necessary for computers having same Operating System in which the code of the java is Created and Executed After Compilation of the Java Program We easily Convert the Program of the java top the another Computer for Execution.

    3) Object-Oriented:- We Know that is purely OOP Language that is all the Code of the java Language is Written into the classes and Objects So For This feature java is Most Popular Language because it also Supports Code Reusability, Maintainability etc.

    4) Robust and Secure:- The Code of java is Robust andMeans ot first checks the reliability of the code before Execution When We trying to Convert the Higher data type into the Lower Then it Checks the Demotion of the Code the It Will Warns a User to Not to do this So it is called as Robust Secure : When We convert the Code from One Machine to Another the First Check the Code either it is Effected by the Virus or not or it Checks the Safety of the Code if code contains the Virus then it will never Executed that code on to the Machine.

    5) Distributed:- Java is Distributed Language Means because the program of java is compiled onto one machine can be easily transferred to machine and Executes them on another machine because facility of Bytes Codes So java is Specially designed For Internet Users which uses the Remote Computers For Executing their Programs on local machine after transferring the Programs from Remote Computers or either from the internet.

    6) Simple Small and Familiar:- is a simple Language Because it contains many features of other Languages like c and C++ and Java Removes Complexity because it doesn’t use pointers, Storage Classes and Go to Statements and java Doesn’t support Multiple Inheritance

    7) Multithreaded and Interactive:- Java uses Multithreaded Techniques For Execution Means Like in other in Structure Languages Code is Divided into the Small Parts Like These Code of java is divided into the Smaller parts those are Executed by java in Sequence and Timing Manner this is Called as Multithreaded In this Program of java is divided into the Small parts those are Executed by Compiler of java itself Java is Called as Interactive because Code of java Supports Also CUI and Also GUI Programs

    8) Dynamic and Extensible Code:- Java has Dynamic and Extensible Code Means With the Help of OOPS java Provides Inheritance and With the Help of Inheritance we Reuse the Code that is Pre-defined and Also uses all the built in Functions of java and Classes

    9) Distributed:- Java is a distributed language which means that the program can be design to run on computer networks. Java provides an extensive library of classes for communicating ,using TCP/IP protocols such as HTTP and FTP. This makes creating network connections much easier than in C/C++. You can read and write objects on the remote sites via URL with the same ease that programmers are used to when read and write data from and to a file. This helps the programmers at remote locations to work together on the same project.

    10) Secure: Java was designed with security in mind. As Java is intended to be used in networked/distributor environments so it implements several security mechanisms to protect you against malicious code that might try to invade your file system.

    For example: The absence of pointers in Java makes it impossible for applications to gain access to memory locations without proper authorization as memory allocation and referencing model is completely opaque to the programmer and controlled entirely by the underlying run-time platform .

    11) Architectural Neutral: One of the key feature of Java that makes it different from other programming languages is architectural neutral (or platform independent). This means that the programs written on one platform can run on any other platform without having to rewrite or recompile them. In other words, it follows 'Write-once-run-anywhere' approach.

    Java programs are compiled into byte-code format which does not depend on any machine architecture but can be easily translated into a specific machine by a Java Virtual Machine (JVM) for that machine. This is a significant advantage when developing applets or applications that are downloaded from the Internet and are needed to run on different systems.

    12) Portable : The portability actually comes from architecture-neutrality. In C/C++, source code may run slightly differently on different hardware platforms because of how these platforms implement arithmetic operations. In Java, it has been simplified.

    Unlike C/C++, in Java the size of the primitive data types are machine independent. For example, an int in Java is always a 32-bit integer, and float is always a 32-bit IEEE 754 floating point number. These consistencies make Java programs portable among different platforms such as Windows, Unix and Mac . 13) Interpreted : Unlike most of the programming languages which are either complied or interpreted, Java is both complied and interpreted The Java compiler translates a java source file to bytecodes and the Java interpreter executes the translated byte codes directly on the system that implements the Java Virtual Machine. These two steps of compilation and interpretation allow extensive code checking and improved security .

    14) High performance: Java programs are complied to portable intermediate form know as bytecodes, rather than to native machine level instructions and JVM executes Java bytecode on. Any machine on which it is installed. This architecture means that Java programs are faster than program or scripts written in purely interpreted languages but slower than C and C++ programs that compiled to native machine languages.

    Although in the early releases of Java, the interpretation of by bytecode resulted in slow performance but the advance version of JVM uses the adaptive and Just in time (JIT) compilation technique that improves performance by converting Java bytecodes to native machine instructions on the fly.