Develop First App in Android

















1. Android SDK Kit
You can get the latest version of the SDK starter package from the SDK download page. Make sure to download the package that is appropriate for your development computer.
 

2. Installing the ADT Plugin for Eclipse
Follow instruction mentioned at Eclipse ADT Installation and Configuration

3. Launching the Android SDK and AVD Manager
The Android SDK and AVD Manager is the tool that you use to install and upgrade SDK components in your development environment.

You can access the tool in any of three ways:

    * If you are developing in the Eclipse IDE with the ADT Plugin, you can access the tool directly from the Eclipse UI.
    * On Windows only, you can launch he tool by double-clicking a script file.
    * In all environments, you can access the tool from a command line.

Launching from Eclipse/ADT

Calculate GeoDistance between two points using Java

This program help to determine Geo Distance between two points using java.
you have to pass longitude and latitude of two different points as arguments to function Distance

Java Program to calculate Geo Distance between two points :
package com.anuj.utils;

public class GeoDistance {

    private static Double geomile;
    private static Double geokil;
    private static Double NauMile;

    public static void main(String[] args) {

        geomile = distance(32.9697, -96.80322, 29.46786, -98.53506, "M");
        System.out.println(geomile + " Miles\n");
        geokil = distance(32.9697, -96.80322, 29.46786, -98.53506, "K");
        System.out.println(geokil + " Kilometers\n");
        NauMile = distance(32.9697, -96.80322, 29.46786, -98.53506, "N");
        System.out.println(NauMile + " Nautical Miles\n");

    }

    private static double distance(double lat1, double lon1, double lat2,
            double lon2, String unit) {
        double theta = lon1 - lon2;
        double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
                + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
                * Math.cos(deg2rad(theta));
        dist = Math.acos(dist);
        dist = rad2deg(dist);
        dist = dist * 60 * 1.1515;
        if (unit.equals("K")) {
            dist = dist * 1.609344;
        } else if (unit.equals("N")) {
            dist = dist * 0.8684;
        }
        return (dist);
    }

    // converts decimal degrees to radians
    private static double deg2rad(double deg) {
        return (deg * Math.PI / 180.0);
    }

    // converts radians to decimal degrees
    private static double rad2deg(double rad) {
        return (rad * 180.0 / Math.PI);
    }

}


How to capture screen shot of current window using Java

This example uses java.awt.Robot class to capture the screen pixels and returns a BufferedImage. Java.awt.Robot class is used to take the control of mouse and keyboard. Once you get the control, you can do any type of operation related to mouse and keyboard through your java code

Key points to be used :
  1. Create Object of Class Robot
  2. Decide size of window to be captured
  3. Call robot.createScreenCapture to capture image

Java Program to capture screenshot of current Window :

package com.anuj.basic;

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;

public class ScreenShots {
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ScreenShots shots = new ScreenShots();
        try {
            shots.captureScreen("CapturedImage.png");
            System.out.println("Screen shots created successfully");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // take screen shots of current window
    public void captureScreen(String fileName) throws Exception {

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle screenRectangle = new Rectangle(screenSize);
        Robot robot = new Robot();
        BufferedImage image = robot.createScreenCapture(screenRectangle);
        ImageIO.write(image, "png", new File(fileName));

    }
}


Merge two PDF into one and Split one PDf into two PDF using java

In order to use this code you need open source lib iText.jar.you can download using link mentioned in my one of blog post "Generate PDf using java".

ConcatPDFs function helps you to merger two pdf say anuj1.pdf and anuj2.pdf into anujmerge.

Using function split pdf,you can split existing one pdf( say having 2 pages) into two seperate pdf say,output1.pdf(page 1 to 1) and output2.pdf(page 2 to 2).

Create PDF File using Java

iText is basically PDF library using which one can
  • Generate documents and reports based xml or database
  • One can add bookmarks, page numbers, watermarks, and other features in existing pdf documents
  • Create PDF document with pages
  • Split or merge pages
  • Serve PDF to browsers
There are other features provided by iText. Please refer to  iText Site for more details.

Please note that example mentioned here is only for learning purpose and You should refer to iText licensing before using.

Java program to create PDF using Java and iText follows as :

J2ME - Read and write using RMS

This is sample application to read and write record using RMS in J2ME mobie application


import javax.microedition.rms.*;

import javax.microedition.rms.*;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;

public class ReadWrite extends MIDlet
{
private RecordStore rs = null;
static final String REC_STORE = "db_1";

public ReadWrite()
{
openRecStore(); // Create the record store

// Write a few records and read them back
writeRecord("J2ME and MIDP");
writeRecord("Wireless Technology");
readRecords();

closeRecStore(); // Close record store
deleteRecStore(); // Remove the record store
}

public void destroyApp( boolean unconditional )
{
}

public void startApp()
{
// There is no user interface, go ahead and shutdown
destroyApp(false);
notifyDestroyed();
}

public void pauseApp()
{
}

public void openRecStore()
{
try
{
// The second parameter indicates that the record store
// should be created if it does not exist
rs = RecordStore.openRecordStore(REC_STORE, true );
}
catch (Exception e)
{
db(e.toString());
}
}

public void closeRecStore()
{
try
{
rs.closeRecordStore();
}
catch (Exception e)
{
db(e.toString());
}
}

public void deleteRecStore()
{
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore(REC_STORE);
}
catch (Exception e)
{
db(e.toString());
}
}
}

public void writeRecord(String str)
{
byte[] rec = str.getBytes();

try
{
rs.addRecord(rec, 0, rec.length);
}
catch (Exception e)
{
db(e.toString());
}
}

public void readRecords()
{
try
{
// Intentionally make this too small to test code below
byte[] recData = new byte[5];
int len;

for (int i = 1; i <= rs.getNumRecords(); i++) { if (rs.getRecordSize(i) > recData.length)
recData = new byte[rs.getRecordSize(i)];

len = rs.getRecord(i, recData, 0);
System.out.println("Record #" + i + ": " + new String(recData, 0, len));
System.out.println("------------------------------");
}
}
catch (Exception e)
{
db(e.toString());
}
}

private void db(String str)
{
System.err.println("Msg: " + str);
}
}

Develop Charts in JSP and Java

I have just used Jfreechart and developed Pie chart displayed on JSP webpage deployed on tomcat.
If you need any assistance/code for this. then tweet me

Apache PDFBox - Parse PDF to text using java

Apache PDFBox is library which allows you to create PDF documents, manipulate of Existing documents and even extract content from existing documents.

Apache PDFBox provides follwing features :
  • Text Extraction
  • Merging and Splitting
  • Forms Filling
  • PDF Printing
  • PDF/A Validations
  • PDF To Image Conversion
  • PDF Creation
  • Integration with Lucene Search Engine
As mentioned in below example PDFTextParser Class takes Pdf as input and parse provided pdf document into text.

Please refer to Following before Using :

Hibernet and Hibernet Dialect Properties


Hibernate supports many database.
Following are list of databases dialect type property:

* DB2 - org.hibernate.dialect.DB2Dialect
* HypersonicSQL - org.hibernate.dialect.HSQLDialect
* Informix - org.hibernate.dialect.InformixDialect
* Ingres - org.hibernate.dialect.IngresDialect
* Interbase - org.hibernate.dialect.InterbaseDialect
* Pointbase - org.hibernate.dialect.PointbaseDialect
* PostgreSQL - org.hibernate.dialect.PostgreSQLDialect
* Mckoi SQL - org.hibernate.dialect.MckoiDialect
* Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect

Linked List using java

Linked list  is implementation of the List interface. LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list

Hierarchies of LinkedList follows as :

java.lang.Object
  extended by java.util.AbstractCollection
      extended by java.util.AbstractList
          extended by java.util.AbstractSequentialList
              extended by java.util.LinkedList
I have list down Linked list methods which are provided as LinkList J2SE6 API documentation
so one can get basic idea what are the methods available and there is simple java program provided
at bottom of current  linkedlist post so you can  play with other methods.

Stack using java

A Stack is like a bucket in which you can put elements one-by-one in sequence and retrieve elements from the bucket according to the sequence of the last entered element. Stack is a collection of data and follows the LIFO (Last in, first out) rule that mean you can insert the elements one-by-one in sequence and the last inserted element can be retrieved at once from the bucket. Elements are inserted and retrieved to/from the stack through the push() and pop() method.

Using Following Stack Java Program , You will be able to do as :
  1. Add elements into stack
  2. Read all elements from Stack
  3. Remove elements from Stack
  4. Get element at specific index in Stack
  5. Check capacity of Stack
  6. Check that Wether Stack contains specific element or not
  7. Clear the Stack
  8. Check that Stack is empty or not

Vector Example using java

The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.

Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement.

Display System Properties using java

The System class contains several useful class fields and methods. It cannot be instantiated.

some of facilities provided by System class are standard input, standard output, error output streams,access to externally defined properties and environment variables etc

System Class provided method called getProperties() to get current system properties.

Properties getProperties()- Determines the current system properties.Please note that return types of this method is Properties. In order to display retirved properties, you need to iterate using example shown at below

Read and Write Excel using Java

To run this u will require jxl.jar

Create.java
------------------------
import java.io.*;
import jxl.*;
import java.util.*;
import jxl.Workbook;
import jxl.write.Number;
import jxl.write.*;

class Create {
public static void main(String[] args) {
try {
String filename = "input.xls";
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(new File(
filename), ws);
WritableSheet s = workbook.createSheet("Sheet1", 0);
WritableSheet s1 = workbook.createSheet("Sheet1", 0);
writeDataSheet(s);
writeImageSheet(s1);
workbook.write();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}

private static void writeDataSheet(WritableSheet s) throws WriteException {

/* Format the Font */
WritableFont wf = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.BOLD);
WritableCellFormat cf = new WritableCellFormat(wf);
cf.setWrap(true);

/* Creates Label and writes date to one cell of sheet */
Label l = new Label(0, 0, "Date", cf);
s.addCell(l);
WritableCellFormat cf1 = new WritableCellFormat(DateFormats.FORMAT9);

DateTime dt = new DateTime(0, 1, new Date(), cf1, DateTime.GMT);

s.addCell(dt);

/* Creates Label and writes float number to one cell of sheet */
l = new Label(2, 0, "Float", cf);
s.addCell(l);
WritableCellFormat cf2 = new WritableCellFormat(NumberFormats.FLOAT);
Number n = new Number(2, 1, 3.1415926535, cf2);
s.addCell(n);

n = new Number(2, 2, -3.1415926535, cf2);
s.addCell(n);

/*
* Creates Label and writes float number upto 3 decimal to one cell of
* sheet
*/
l = new Label(3, 0, "3dps", cf);
s.addCell(l);
NumberFormat dp3 = new NumberFormat("#.###");
WritableCellFormat dp3cell = new WritableCellFormat(dp3);
n = new Number(3, 1, 3.1415926535, dp3cell);
s.addCell(n);

/* Creates Label and adds 2 cells of sheet */
l = new Label(4, 0, "Add 2 cells", cf);
s.addCell(l);
n = new Number(4, 1, 10);
s.addCell(n);
n = new Number(4, 2, 16);
s.addCell(n);
Formula f = new Formula(4, 3, "E1+E2");
s.addCell(f);

/* Creates Label and multipies value of one cell of sheet by 2 */
l = new Label(5, 0, "Multipy by 2", cf);
s.addCell(l);
n = new Number(5, 1, 10);
s.addCell(n);
f = new Formula(5, 2, "F1 * 3");
s.addCell(f);

/* Creates Label and divide value of one cell of sheet by 2.5 */
l = new Label(6, 0, "Divide", cf);
s.addCell(l);
n = new Number(6, 1, 12);
s.addCell(n);
f = new Formula(6, 2, "F1/2.5");
s.addCell(f);
}

private static void writeImageSheet(WritableSheet s) throws WriteException {
/* Creates Label and writes image to one cell of sheet */
Label l = new Label(0, 0, "Image");
s.addCell(l);
WritableImage wi = new WritableImage(0, 3, 5, 7, new File(
"D:\\eclipseWorkspace1\\Excel\\src\\ad_flag.png"));
s.addImage(wi);

/* Creates Label and writes hyperlink to one cell of sheet */
l = new Label(0, 15, "HYPERLINK");
s.addCell(l);
Formula f = new Formula(1, 15,
"HYPERLINK(\"http://www.google.com\", "
+ "\"Anuj\")");
s.addCell(f);

}

}


Java StringBuffer Example

StringBuffer Class is mutable sequence of characters.It's like String but content of String can be modified after creation.

Using StringBuffer different methods you can :
  1. append String to existing String append() method
  2. insert String at specific index using insert() method
  3. reverse String using reverse() method.
  4. Find character position within String
  5. set character at Specific index
  6. delete character at specific index
  7. get subString using specific index
  8. delete characters within String
  9. find String buffer capacity
Java Program to StringBuffer methods example :

Check URL Exists or not In Java

In order to check that url exsists or not, you need to do following.
  • Create instance of URL
  • Open connection to url using url.openConnection
  • Create instance of HttpURLConnection
  • Check that httpURLConnection.getResponseCode() is equal to 200 or not.