Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, 8 September 2016

Android Tutorial #2 (Basic components of Android)



Android

This tutorial helps you understand in depth the basic components of an Android application.

Components


1. Java files

Java is a programming language and computing platform first released by Sun Microsystems in 1995.
The Java files contain pieces of code that define how the Android application will react to events at run-time.
The Java files put life into the basic skeleton provided by the layouts allowing the user to interact with the Android application.

App components are the building blocks of an Android application. The system can enter the application from each component, however not all components are user entry points. Each component exists on its own and performs a specific task. Hence basically an Android application is a collection of one or more App components interacting with each other in order to perform specific functions.
There are four type of App components :

A. Activity

The Activity class in Android represents a single screen. Every Java program starts execution from the main function, similarly an Activity starts execution from the onCreate() method. The lifecycle of an Activity is as given below



B. Service 

A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface.
There are two types of services :
    1. Bounded Service
An application component can bind a service by calling bindService(), such a service offers a client-server interface that allows components to interact with the service, send requests, get results and even supports Inter Process Communication (IPC). The service is bound to the application component that started it and dies when the corresponding application component dies.

    2. Unbounded Service
An unbounded service is started when an application component, such as an activity starts it by calling startService(). Once started a service can run in the background indefinitely, even if the component that started it is destroyed.

Lifecycle of a service is given below.


C. Content Providers

A Content Provider manages a shared set of app data. Data can be stored in the file system, an SQLite database, on the web or any other persistent storage location the application can access. Content providers are useful for reading and writing data that is private to your app and not shared. It is implemented as a subclass of ContentProvider.


D. Broadcast Receivers

It responds to a system-wide broadcast announcements, these include broadcasts announcing that the battery is low, screen is turned off, etc. The application can also initiate custom broadcasts. Broadcast Receivers don't create a user interface, they may create a status bar notification. A broadcast receiver can be thought of as a gateway to other components and is intended to do a minimal amount of work.

2. Resource files

Resource files are present in the resource folder. They form the skeleton of the Android application. This resource folder consists of various subfolders such as

A. drawable


The drawable folder consists of all the drawable files in the Android application.
In order to optimise the UI for different screen sizes the drawables need to be used
according to screen size. To do this we use the following folders
1. drawable-ldpi 
2. drawable-mdpi
3. drawable-hdpi
4. drawable-xhdpi
5. drawable-xxhdpi

LDPI, MDPI, HDPI, XHDPI, XXHDPI refers to screen density, which means how
many pixels can fit in once inch.
The ratio in pixels between them is
1. ldpi - 1:0.75 (low dot per inch)
2. mdpi - 1:1 (medium dot per inch)
3. hdpi - 1:1.5 (high dot per inch)
4. xhdpi - 1:2 (extra high dot per inch)
5. xxhdpi - 1:3 (extra extra high dot per inch.


B. layout

The layout folder contains layout files (.xml extension) that basically define the structure of the UI of the android application. The layouts form the skeleton of the Android application which is given life by the Java files. The layout file consists of views, these views are called the children of the layout. 
The View object is the basic building block of the UI which is created from the View Class and it occupies a rectangular area the screen and is responsible for drawing and event handling. The base class for widgets is View, and these widgets are used to create interactive UI components like buttons, text fields, etc.
There are five standard layouts :
    1. Linear Layout :
Arranges it's children in a single column or row. The orientation of the row can be set using the orientation attribute.

    2. Relative Layout :
Displays the child views in relative positions. The position of each child can be specified as relative to a sibling view.

    3. Frame Layout :
Used to block out an area on the screen to display a single item. Child views are drawn in stack with the most recent views drawn on top. This can be used to draw multiple views overlapping each other.

    4. Absolute Layout :
It allows you to specify exact locations of it's children using x, y co-ordinates.


    5. Table Layout :
Allows you to arrange groups of views in rows and columns.


C. menu

It consists of Menu Resource files. A Menu Resource file is a .xml file which defines an application menu such as an Options menu, Context menu, submenu that can be inflated
using MenuInflator.


D. mipmap

The Mipmap folder is used to place application/ launch icons. Similar to the drawables folder they have different subfolders mipmap-ldpi, mipmap-mdpi, mipmap-hdpi, etc. for different screen resolutions. 


E. values


The values folder contains various constant values that you keep using through the course of the application. For example it may contain constant strings.xml file which stores constant strings that are used throughout the program. It provides a single point of access to values that may be used from different parts of the application avoiding the creation of multiple variables. To retrieve string from strings.xml we can use "R.string.string_name". Similarly we can have a dimens.xml file which allows us to associate names with various dimension values.
The values folder may have different subfolders for different screen resolutions.


Wednesday, 7 September 2016

Android Tutorial #1

Android

Android is a mobile Operating System (OS) developed by Google and it's based on the Linux Kernel. It's designed mainly for touchscreen phones. It is an open source initiative and the Android source code is released by Google under the Open Source licences.

Components

So at a very abstract level developing Android applications consists of two components :
1) Resource files.
2) Java files.

1.Resource Files

Resource files are stored under the res directory and can be considered as the skeleton of the Android application.

2.Java Files

Java files are stored in the java directory and are used to add life to the Android application and make it respond to dynamic events.


Other than this broad categorisation there are other types of files which will be explained in the coming parts.


Example

Without spending more time on the nitty gritty's lets begin writing your first Android application.

Since Android has stopped support for Eclipse I urge you to use Android Studio and this tutorial will contain screenshots of projects in Android studio.


After installing Android Studio and setting up your SDK, start Android Studio.



 Click on the "Start a new Android Studio project " option under "Quick Start".


Fill up the field "Application name" with something suitable.
"Company Domain" should be the web domain name of your company so that it is unique, however it is not necessary for the domain to exists. The "Package name" depends on the "Company Domain" you provide which in turn is used to name your package and while uploading your .apk file to the Google Playstore. So as of now you needn't worry about it.

After filling up the data suitably click "Next".


Check the "Phone and Tablet" checkbox since we are going to develop and Android application for a phone/tablet in this tutorial.

The other check boxes need to be checked when developing applications for the respective devices as suggested in the name. Wear for watches, TV for televisions, etc.

 Depending on the SDK you have downloaded set up the "Minimum SDK"."The Minimum SDK" means that the application we are building will work only on devices running at least this version of Android.

Click the next button after filling up all the details.


Activity
An Activity is an application component that provides a screen with which users can interact in order to do something , such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.

Android Studio allows us to chose from a set of Activity templates. We will choose the "Blank Activity" for now and we will use the other templates in further tutorials.

Click the "Next" button after choosing the "Blank Activity".


Usually most Android applications begin with an Activity called "MainActivity". This name can be changed. For the purpose of maintaining uniformity it will be kept as "MainActivity" in this example.
Each Activity has a Layout file (XML Layout) associated with it.
The field "Layout Name" denotes the name of the XML Layout associated with this Activity. 
As the complexity of your program increases and more complex components are added it becomes difficult to maintain the code, hence the prefix "activity" is added before the layout name. It is not compulsory but it is recommended.
The field "Menu Resource Name" contains the name of an XML Resource file. This file contains a number of constants which are used to populate and Options Menu, Context Menu, submenu, etc.
These constants cane be referenced from the Java files.

Click "Finish" to create your First Android project.






Connect an Android device to your computer. As you connect the device you will get a pop-up asking you to enable "USB Debugging". Enable USB Debugging on your device.
Click the Green Play button which is within the red circle in the previous screenshot.
If you do not have an android device you can create an Android Virtual Device by clicking on AVD which is within the blue circle in the previous screenshot.
Click here to learn how to create your Android Virtual Device.

Congratulations!!

You successfully created your first Android Application.
The next tutorial will contain a detailed analysis of the code explaining key concepts. 
Until then
DREAM OF CODE.

Sunday, 1 November 2015

Virtual Canvas

//Filename : FingerBall.java and PongCanvas.java
/* Virtual Canvas . The Virtual Canvas allows the user to draw in 3D space without the need of any wearable device, it uses a tool ,which is nothing but an elongated stick to draw in 3D space.
Requirements:Leap Motion Controller
Youtube Link of the video : https://youtu.be/RF2lRllYuOE
+Leap Motion
+Leap Motion Developers
*/


//FingerBall.java

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import com.leapmotion.leap.*;
import com.leapmotion.leap.Controller.PolicyFlag;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
class Sample extends Listener {
public void onConnect(Controller controller) {
System.out.println("Connnected");
controller.enableGesture(Gesture.Type.TYPE_CIRCLE);
controller.enableGesture(Gesture.Type.TYPE_KEY_TAP);
controller.enableGesture(Gesture.Type.TYPE_SCREEN_TAP);
controller.enableGesture(Gesture.Type.TYPE_SWIPE);
}
public void onInitialise() {
System.out.println("Initialised");
}
public void onFrame(Controller controller) {

}
}
public class FingerBall {
public static void main(String[] args) throws Exception {
Sample listener = new Sample();
PongCanvas fc = new PongCanvas();
java.awt.Frame f = new java.awt.Frame();
Controller controller = new Controller();
controller.policyFlags();
controller.setPolicyFlags(PolicyFlag.POLICY_BACKGROUND_FRAMES);
controller.addListener(listener);
System.out.println("Press Enter to quit...");
try {
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setLocation(0, 0);
f.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
f.setBackground(Color.black);
fc.start();
f.add(fc);
f.pack();
f.setVisible(true);
System.in.read();
} catch (IOException e) {
}
controller.removeListener(listener);
}
}



// PongCanvas.java

import java.awt.Canvas;
import com.leapmotion.leap.*;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class PongCanvas extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
private Rectangle rect = null;
private Thread looper;
private boolean running;
private int diameter;
private BufferedImage bufferedimage;
static int ch = 0;
Hand hand[] = new Hand[5];
Finger finger[][] = new Finger[5][15];
Pointable pointable = new Pointable();
int xCurrent2 = 0;
int yCurrent2 = 0;
int checker = 0;
static Graphics g1 = null;
PongCanvas() {
setSize(java.awt.Frame.MAXIMIZED_HORIZ, java.awt.Frame.MAXIMIZED_VERT);
}
public void init() {
}
public void start() {
if (!running) {
running = true;
looper = new Thread(this);
looper.start();
}
}
public void stop() {
running = false;
}
public void captureScreen() throws Exception {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd hh mm ss a");
Calendar now = Calendar.getInstance();
Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(new Rectangle(20,
20, 1330, 700));
ImageIO.write(screenShot, "PNG", new File("/Users/mohammedalichherawalla/Documents/workspace/UtilityKit/images/"
+ formatter.format(now.getTime()) + ".png"));

}
public void run() {
try {
Controller controller = new Controller();
while (running) {
Frame frame = controller.frame();
GestureList gestures = frame.gestures();
Gesture gesture = gestures.get(0);
Gesture gesture1 = gestures.get(1);
Gesture gesture2 = gestures.get(2);
if (gesture.type() == Gesture.Type.TYPE_KEY_TAP
|| gesture1.type() == Gesture.Type.TYPE_KEY_TAP
|| gesture2.type() == Gesture.Type.TYPE_KEY_TAP) {
captureScreen();
ch = 3;

} else if (gesture.type() == Gesture.Type.TYPE_SCREEN_TAP
|| gesture1.type() == Gesture.Type.TYPE_SCREEN_TAP
|| gesture2.type() == Gesture.Type.TYPE_SCREEN_TAP) {
ch = 1;

} else if (gesture.type() == Gesture.Type.TYPE_SWIPE
|| gesture1.type() == Gesture.Type.TYPE_SWIPE
|| gesture2.type() == Gesture.Type.TYPE_SWIPE) {
ch = 2;
}
repaint();
}
} catch (Exception e) {
running = false;
}
}
public void update(Graphics g) {
if (!getBounds().equals(rect)) {
rect = getBounds();
diameter = 30;
bufferedimage = new BufferedImage(1366, 768,
BufferedImage.TYPE_INT_RGB);
}
if (running) {
paint(bufferedimage.getGraphics());
g.drawImage(bufferedimage, 0, 0, null);
}
}
public void paint(Graphics g) {
if (rect == null) {
return;
}
g1 = g;
Controller controller = new Controller();
Frame frame = controller.frame();
HandList allHands = frame.hands();
int countOfHands = allHands.count();
FingerList allFingers = frame.fingers();
int countOfFingers = allFingers.count();
if (ch == 0) {
g.setColor(Color.blue);
Font monoFont = new Font("Monospaced", Font.BOLD | Font.ITALIC, 36);
g.setColor(Color.white);
g.setFont(monoFont);
FontMetrics fm = g.getFontMetrics();
fm.stringWidth("Virtual Canvas ");
fm.getAscent();
g.drawString("Virtual Canvas", 120, 50);
fm.stringWidth("Screen Tap to clear screen ");
fm.getAscent();
g.drawString("Screen Tap to clear screen", 120, 150);
fm.stringWidth("Virtual Canvas ");
fm.getAscent();
g.drawString("Key press to save work", 120, 250);
fm.stringWidth("Key press to save work");
fm.getAscent();
g.drawString("Swipe to start Virtual Canvas !", 120, 350);
}
else if (ch == 1) {
int xCurrent1 = 0;
int yCurrent1 = 0;
g.setColor(Color.black);
g.fillRect(0, 0, rect.width, rect.height);
}
else if (ch == 2) {
int xCurrent1 = 0;
int yCurrent1 = 0;
g.setColor(Color.black);
g.fillRect(0, 0, 1360, 60);
g.setColor(Color.blue);
Font monoFont = new Font("Monospaced", Font.BOLD | Font.ITALIC, 36);
g.setColor(Color.white);
g.setFont(monoFont);
FontMetrics fm = g.getFontMetrics();
fm.stringWidth("Virtual Canvas ");
fm.getAscent();
g.drawString("Virtual Canvas", 120, 50);
PointableList p = frame.pointables();
int countOfPointables = p.count();
int type1 = 0;
int i = 0;
if (frame.pointables().get(0).isTool())
{
pointable = frame.pointables().get(0);
xCurrent1 = (int) pointable.tipPosition().getX() + 550;
yCurrent1 = 600 - (int) pointable.tipPosition().getY();
diameter=(int) pointable.tipPosition().getZ();;
diameter/=7;
if(diameter<5){
diameter=5;
}
g.setColor(Color.white);
g.drawRect((int) xCurrent1, (int) yCurrent1, diameter,
diameter );

}
} else if (ch == 3) {
g.setColor(Color.black);
g.fillRect(0, 0, 1360, 766);

g.setColor(Color.blue);
Font monoFont = new Font("Monospaced", Font.BOLD | Font.ITALIC, 36);
g.setColor(Color.white);
g.setFont(monoFont);
FontMetrics fm = g.getFontMetrics();
fm.stringWidth("Saved ");
fm.getAscent();
g.drawString("Saved", 120, 50);
}

}
}

Saturday, 31 October 2015

Queue Implementation in Java

//Filename : QueueExample.java
// Program to implement Queue data structure in java

import java.util.*;
class arrayQueue
{
    protected int Queue[] ;
    protected int front, rear, size, len;
    public arrayQueue(int n)
    {
        size = n;
        len = 0;
        Queue = new int[size];
        front = -1;
        rear = -1;
    }  
    public boolean isEmpty()
    {
        return front == -1;
    }  
    public boolean isFull()
    {
        return front==0 && rear == size -1 ;
    }  
    public int getSize()
    {
        return len ;
    }  
    public int peek()
    {
        if (isEmpty())
           throw new NoSuchElementException("Underflow Exception");
        return Queue[front];
    }  
    public void insert(int i)
    {
        if (rear == -1)
        {
            front = 0;
            rear = 0;
            Queue[rear] = i;
        }
        else if (rear + 1 >= size)
            throw new IndexOutOfBoundsException("Overflow Exception");
        else if ( rear + 1 < size)
            Queue[++rear] = i;  
        len++ ;  
    }  
    public int remove()
    {
        if (isEmpty())
           throw new NoSuchElementException("Underflow Exception");
        else
        {
            len-- ;
            int ele = Queue[front];
            if ( front == rear)
            {
                front = -1;
                rear = -1;
            }
            else
                front++;              
            return ele;
        }      
    }
    public void display()
    {
        System.out.print("\nQueue = ");
        if (len == 0)
        {
            System.out.print("Empty\n");
            return ;
        }
        for (int i = front; i <= rear; i++)
            System.out.print(Queue[i]+" ");
        System.out.println();      
    }
}
public class QueueExample
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);

        System.out.println("Array Queue Test\n");
        System.out.println("Enter Size of Integer Queue ");
        int n = scan.nextInt();
        arrayQueue q = new arrayQueue(n);      
        char ch;
        do{
            System.out.println("\nQueue Operations");
            System.out.println("1. insert");
            System.out.println("2. remove");
            System.out.println("3. peek");
            System.out.println("4. check empty");
            System.out.println("5. check full");
            System.out.println("6. size");
            int choice = scan.nextInt();
            switch (choice)
            {
            case 1 :
                System.out.println("Enter integer element to insert");
                try
                {
                    q.insert( scan.nextInt() );
                }
                catch(Exception e)
                {
                    System.out.println("Error : " +e.getMessage());
                }                      
                break;                      
            case 2 :
                try
                {
                    System.out.println("Removed Element = "+q.remove());
                }
                catch(Exception e)
                {
                    System.out.println("Error : " +e.getMessage());
                }
                break;                      
            case 3 :
                try
                {
                    System.out.println("Peek Element = "+q.peek());
                }
                catch(Exception e)
                {
                    System.out.println("Error : "+e.getMessage());
                }
                break;                          
            case 4 :
                System.out.println("Empty status = "+q.isEmpty());
                break;              
            case 5 :
                System.out.println("Full status = "+q.isFull());
                break;                        
            case 6 :
                System.out.println("Size = "+ q.getSize());
                break;                      
            default : System.out.println("Wrong Entry \n ");
                break;
            }
            q.display();          
            System.out.println("\nDo you want to continue (Type y or n) \n");
            ch = scan.next().charAt(0);

        } while (ch == 'Y'|| ch == 'y');                                                      
    }  
}

Stack implementation in Java

//FileName: StackExample.java
//Program to implement stack in java .


import java.util.*;
class arrayStack
{
    protected int arr[];
    protected int top, size, len;
    public arrayStack(int n)
    {
        size = n;
        len = 0;
        arr = new int[size];
        top = -1;
    }
    public boolean isEmpty()
    {
        return top == -1;
    }
    public boolean isFull()
    {
        return top == size -1 ;      
    }
    public int getSize()
    {
        return len ;
    }
    public int peek()
    {
        if( isEmpty() )
            throw new NoSuchElementException("Underflow Exception");
        return arr[top];
    }
    public void push(int i)
    {
        if(top + 1 >= size)
            throw new IndexOutOfBoundsException("Overflow Exception");
        if(top + 1 < size )
            arr[++top] = i;
        len++ ;
    }
    public int pop()
    {
        if( isEmpty() )
            throw new NoSuchElementException("Underflow Exception");
        len-- ;
        return arr[top--];
    }  
    public void display()
    {
        System.out.print("\nStack = ");
        if (len == 0)
        {
            System.out.print("Empty\n");
            return ;
        }
        for (int i = top; i >= 0; i--)
            System.out.print(arr[i]+" ");
        System.out.println();
    }  
}
public class StackExample
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);      
        System.out.println("Stack Test\n");
        System.out.println("Enter Size of Integer Stack ");
        int n = scan.nextInt();
        arrayStack stk = new arrayStack(n);
        char ch;
        do{
            System.out.println("\nStack Operations");
            System.out.println("1. push");
            System.out.println("2. pop");
            System.out.println("3. peek");
            System.out.println("4. check empty");
            System.out.println("5. check full");
            System.out.println("6. size");
            int choice = scan.nextInt();
            switch (choice)
            {
            case 1 :
                System.out.println("Enter integer element to push");
                try
                {
                    stk.push( scan.nextInt() );
                }
                catch (Exception e)
                {
                    System.out.println("Error : " + e.getMessage());
                }                      
                break;                      
            case 2 :
                try
                {
                    System.out.println("Popped Element = " + stk.pop());
                }
                catch (Exception e)
                {
                    System.out.println("Error : " + e.getMessage());
                }  
                break;                      
            case 3 :      
                try
                {
                    System.out.println("Peek Element = " + stk.peek());
                }
                catch (Exception e)
                {
                    System.out.println("Error : " + e.getMessage());
                }
                break;                      
            case 4 :
                System.out.println("Empty status = " + stk.isEmpty());
                break;              
            case 5 :
                System.out.println("Full status = " + stk.isFull());
                break;              
            case 6 :
                System.out.println("Size = " + stk.getSize());
                break;                      
            default :
                System.out.println("Wrong Entry \n ");
                break;
            }
            stk.display();          
            System.out.println("\nDo you want to continue (Type y or n) \n");
            ch = scan.next().charAt(0);

        } while (ch == 'Y'|| ch == 'y');              
    }
}