Friday, 22 August 2014

How to find Bluetooth device services in Java

Leave a Comment
Today I'm going to demonstrate "How to use BlueCove to search near by Bluetooth devices?" and "How to find Bluetooth device services in Java using BlueCove".
It is a Java library for Bluetooth (JSR-82 implementation) that currently interfaces with the Mac OS X, WIDCOMM, BlueSoleil and Microsoft Bluetooth stack found in Windows XP SP2 or Windows Vista and WIDCOMM and Microsoft Bluetooth stack on Windows Mobile.
How to find Bluetooth device services in Java,find Bluetooth device services in Java,Bluetooth device services in Java,device services in Java,services in Java,How to use BlueCove to search near by Bluetooth devices,BlueCove to search near by Bluetooth devices,search near by Bluetooth devices,search near by Bluetooth devices in java,

RemoteDeviceDiscovery class is used to find paired and near by devices.
import java.util.Enumeration;
import java.util.Vector;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;

public class RemoteDeviceDiscovery {

    public Vector getDevices() {
        /* Create Vector variable */
        final Vector devicesDiscovered = new Vector();
        try {
            final Object inquiryCompletedEvent = new Object();
            /* Clear Vector variable */

            /* Create an object of DiscoveryListener */
            DiscoveryListener listener = new DiscoveryListener() {

                public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
                    /* Get devices paired with system or in range(Without Pair) */

                public void inquiryCompleted(int discType) {
                    /* Notify thread when inquiry completed */
                    synchronized (inquiryCompletedEvent) {

                /* To find service on bluetooth */
                public void serviceSearchCompleted(int transID, int respCode) {

                /* To find service on bluetooth */
                public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {

            synchronized (inquiryCompletedEvent) {
                /* Start device discovery */
                boolean started = LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(DiscoveryAgent.GIAC, listener);
                if (started) {
                    System.out.println("wait for device inquiry to complete...");
        } catch (Exception e) {
        /* Return list of devices */
        return devicesDiscovered;
ServicesSearch class used to find specific service on Bluetooth device. Each service identified using UUID (Universally unique identifier).
All UUID listed on .
Replace your required UUID in following code.
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.bluetooth.*;

public class ServicesSearch {

     * UUID used to find specific service supported by bluetooth device
     * Find UUIDs for all types of bluetooth services.
    /* To find push object service */
    private UUID OBEX_OBJECT_PUSH_PROFILE = new UUID(0x1105);
    /* To find file transfer service */
    private UUID OBEX_FILE_TRANSFER_PROFILE = new UUID(0x1106);
    /* To find hands free service */
    private UUID HANDS_FREE = new UUID(0x111E);
    /* Get URL attribute from bluetooth service */
    private int URL_ATTRIBUTE = 0X0100;
    public Map<String, List<String>> getBluetoothDevices() {        
         * Find service on bluetooth device 
         * Note: In following line you can use one service at a time. I'm new to bluetooth programming it might me wrong perception.
         * UUID[] searchUuidSet = new UUID[]{OBEX_FILE_TRANSGER_PROFILE};
         * CORRECT: UUID[] searchUuidSet = new UUID[]{OBEX_FILE_TRANSGER_PROFILE};
        /* Initialize UUID Array */
        UUID[] searchUuidSet = new UUID[]{HANDS_FREE};
        final Object serviceSearchCompletedEvent = new Object();
        int[] attrIDs = new int[]{URL_ATTRIBUTE};
        /* Create an object to get list of devices in range or paired */
        RemoteDeviceDiscovery remoteDeviceDiscovery = new RemoteDeviceDiscovery();
        /* Create map to return Bluetooth device address, name and URL */
        final Map<String, List<String>> mapReturnResult = new HashMap<String, List<String>>(); 

        try {
            /* Create an object of DiscoveryListener */
            DiscoveryListener listener = new DiscoveryListener() {

                /* To find bluetooth devices */
                public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {

                /* To find bluetooth devices */
                public void inquiryCompleted(int discType) {

                /* Find service URL of bluetooth device */
                public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
                    for (int i = 0; i < servRecord.length; i++) {
                        /* Find URL of bluetooth device */
                        String url = servRecord[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                        if (url == null) {
                        String temporaryString = "";
                        /* Get object of bluetooth device */
                        RemoteDevice rd = servRecord[i].getHostDevice();
                        /* Get attribute from ServiceRecord */
                        DataElement serviceName = servRecord[i].getAttributeValue(URL_ATTRIBUTE);
                        if (serviceName != null) {         
                            temporaryString = serviceName.getValue() + "\n" + url;
                            /* Put it in map */
                        } else {
                            temporaryString = "Uknown service \n" + url;
                            /* Put it in map */

                public void serviceSearchCompleted(int transID, int respCode) {
                    /* Notify thread when search completed */
                    synchronized (serviceSearchCompletedEvent) {

            /* Get list of bluetooth device from class RemoteDeviceDiscovery */
            for (Enumeration en = remoteDeviceDiscovery.getDevices().elements(); en.hasMoreElements();) {
                /* Get RemoteDevice object */
                RemoteDevice btDevice = (RemoteDevice) en.nextElement();
                /* Create list to return details */
                List<String> listDeviceDetails = new ArrayList<String>();
                try {
                    /* Add bluetooth device name and address in list */
                } catch (Exception e) {
                /* Put bluetooth device details in map */
                mapReturnResult.put(btDevice.getBluetoothAddress(), listDeviceDetails);
                synchronized (serviceSearchCompletedEvent) {
                    LocalDevice.getLocalDevice().getDiscoveryAgent().searchServices(attrIDs, searchUuidSet, btDevice, listener);
        } catch (Exception e) {
        /* Return bluetooth devices detail */
        return mapReturnResult;
BluetoothDevices is simple JFrame used to give Uter Interface for program. Its created in NetBeans IDE, You may find some code unexplained which is generated by IDE.
import com.javaquery.bluetooth.ServicesSearch;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.UIManager;

public class BluetoothDevices extends javax.swing.JFrame {

    /* DefaultListModel to attach it with JList */
    private DefaultListModel defaultModel;
    /* Map to get device details list */
    private Map<String, List<String>> mapReturnResult = new HashMap<String, List<String>>();
    /* Map to identify device on user click of JList */
    private Map<Integer, List<String>> mapDevicePosition = new HashMap<Integer, List<String>> ();

    public BluetoothDevices() {
        defaultModel = new DefaultListModel();

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        JListBluetoothDevices = new javax.swing.JList();
        lblDeviceName = new javax.swing.JLabel();
        lblRuntimeDeviceName = new javax.swing.JLabel();
        lblDeviceAddress = new javax.swing.JLabel();
        lblRuntimeDeviceAddress = new javax.swing.JLabel();
        lblServiceDetails = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        JTextAreaServiceDetails = new javax.swing.JTextArea();

        setTitle("Bluecove Bluetooth Discovery");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {

        JListBluetoothDevices.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {

        lblDeviceName.setText("Bluetooth Device Name");

        lblDeviceAddress.setText("Bluetooth Device Address");

        lblServiceDetails.setText("Service Details");


        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(73, 73, 73)
                            .addComponent(lblRuntimeDeviceName, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                        .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)))

    }// </editor-fold>//GEN-END:initComponents

 /* Search for bluetooth device when window opened */
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        int intDevicePosition = 0;

        /* Create an object of ServicesSearch */
        ServicesSearch ss = new ServicesSearch();
        /* Get bluetooth device details */
        mapReturnResult = ss.getBluetoothDevices();

        /* Add devices in JList */
        for (Map.Entry<String, List<String>> entry : mapReturnResult.entrySet()) {            
            mapDevicePosition.put(intDevicePosition, entry.getValue());

 /* On click of any item in List Box */
    private void JListBluetoothDevicesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JListBluetoothDevicesMouseClicked
  /* Get bluetooth device details from temporary list */
        List<String> tmpDeviceDetails = mapDevicePosition.get(JListBluetoothDevices.getSelectedIndex());
  /* Set bluetooth device name */
  /* Set bluetooth device Address */
        if(tmpDeviceDetails.size() > 2 && tmpDeviceDetails.get(2) != null){
   /* Set bluetooth device service name and URL */
            JTextAreaServiceDetails.setText("Service not found");

     * @param args the command line arguments
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                 /* To set new look and feel */
                try {
                     * Change look and feel of JFrame to Nimbus 
                     * For other look and feel check
                } catch (Exception ex) {
                /* Create an object of BluetoothDevices */
                BluetoothDevices bluetoothDevicesFrame = new BluetoothDevices();
                /* make BluetoothDevices visible */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList JListBluetoothDevices;
    private javax.swing.JTextArea JTextAreaServiceDetails;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblDeviceAddress;
    private javax.swing.JLabel lblDeviceName;
    private javax.swing.JLabel lblRuntimeDeviceAddress;
    private javax.swing.JLabel lblRuntimeDeviceName;
    private javax.swing.JLabel lblServiceDetails;
    // End of variables declaration//GEN-END:variables

If you're fine then like and share that post.

Wednesday, 20 August 2014

What are Difference between load( ) vs get( ) in Hibernate

Leave a Comment
The following Hibernate code snippet retrieves a User object from the database:
What are Difference between load( ) vs get( ) in Hibernate,Difference between load( ) vs get( ) in Hibernate,between load( ) vs get( ) in Hibernate,load( ) vs get( ) in Hibernate,get( ) in Hibernate,


1). Only use the load()method if you are sure that the object exists.
2). load() method will throw an exception if the unique id is not found in the database.
3). load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.

Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>
   Item item = session.load(Item.class, itemId);
   Bid bid = new Bid();
} catch(ObjectNotFoundException e) {
   log.error("Bid placed for an unavailable item");
   // Handle the error condition appropriately

get( )

1). If you are not sure that the object exists, then use one of the get() methods.
2). get() method will return null if the unique id is not found in the database.
3). get() will hit the database immediately.

Session session = << Get session from SessionFactory >>
Long itemId = << Get the item id from request >>
Item item = (Item) session.get(Item.class, itemId);
if(item != null) {
   Bid bid = new Bid();
} else {
   log.error("Bid placed for an unavailable item");
   // Handle the error condition appropriately


Disadvantage of Hibernate

Leave a Comment
Hello java developer we all know the advantage of Hibernate but are you aware about disadvantage of Hibernate. If you want to use Hibernate in your program then focused on below statements.
The main disadvantages of Hibernate is given in detail.

1) Steep learning curve.
2) Use of Hibernate is an overhead for the applications which are :

  • simple and use one database that never change
  • need to put data to database tables, no further SQL queries
  • there are no objects which are mapped to two different tables

Disadvantage of Hibernate,hibarnate disadvantage

Hibernate increases extra layers and complexity. So for these types of applications JDBC is the best choice.
3) Support for Hibernate on Internet is not sufficient.
4) Anybody wanting to maintain application using Hibernate will need to know Hibernate.
5) For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion.
6) Hibernate does not allow some type of queries which are supported by JDBC. For example It does not allow to insert multiple objects (persistent data) to same table using single query. Developer has to write separate query to insert each object.


Thursday, 14 August 2014

Chromium WebView - Custom Android WebView

Leave a Comment
When we need a webview in android project. Then we can use webview but when we open our project on below of android version 4.4.x. Some functionality doesn't show on that webview.
And if you want to add the latest browser features in your old android version phone's webview or default browser.

Then answer is Chromium Webview
Are you amaze to hear that how can you make your own custom webview in android ?
You can give the power of google chrome in your old version android webview.
ChormeView works like Android's WebView, but is backed by the latest Chromium code. It lets you ship your own Chromium code, instead of using whatever version comes with your user's Android image. This gives your application early access to the newest features in Chromium, and removes the variability due to different WebView implementations in different versions of Android.
Chromium WebView - Custom Android WebView,WebView - Custom Android WebView,Custom Android WebView,Android WebView,how to create own webview android,create own webview android,own webview android,webview android,

How to setup this  chromium library :

  • Download the library code

First of all  download ChromeView library .

  • Make them library

After that Check out the repository in your Eclipse workspace, and make your project use ChromeView as a library. In Eclipse, right-click your project directory, select Properties, choose the Android category, and click on the Add button in the Library section.

  • Copy Data
Copy assets/webviewchromium.pak to your project's assets directory.
  • Initialize Chromium
Create new java file name MyApplication and initialize chromium

public class MyApplication extends Application {
    public void onCreate() {
Now you can use ChromeView in the same contexts as you would use WebView.

  • Use of ChromeView
in you main_activity.xml
We use instead of WebView like :
And in you 
ChromeView chromeView = (ChromeView)findViewById(;

Note: Don't forget to give INTERNET PERMISSION . 


Monday, 4 August 2014

Top 10 tricky java interview question with answer

Leave a Comment
Hello friends today i am telling you top 10 tricky java question with answer .As per my experience there are always one or two tricky or tough Java interview question on any core Java or J2EE interviews, so its good to prepare tricky questions from Java in advance.

Top 10 tricky java interview question with answer,10 tricky java interview question with answer,tricky java interview question with answer,java interview question with answer,interview question with answer,

Tricky Java interview question and answer for experienced programmer.Here is my list of 10 tricky Java interview questions, Though I have prepared and shared lot of difficult core java interview question and answers, But I have chosen them as Top 10 tricky questions because you can not guess answers of this tricky java questions easily, you need some subtle details of Java programming language to answer these questions.
What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
This is a very popular tricky Java question and its tricky because many programmer think that finally block always executed. This question challenge that concept by putting return statement in try or catch block or calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.

Can you override private or static method in Java ?
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java.  Anyway, you can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding. 

Does Java support multiple inheritance ?
This is the trickiest question in Java, if C++ can support direct multiple inheritance than why not Java is the argument Interviewer often give. 

What will happen if we put a key object in a HashMap which is already there ?
This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys.

If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?
One more tricky Java questions from overloading and overriding concept. Answer is you can very well throw super class of RuntimeException in overridden method but you can not do same if its checked Exception.
What is the issue with following implementation of compareTo() method in Java
public int compareTo(Object o){
   Employee emp = (Employee) emp;
   return -;

Where id is an integer number ?
Well three is nothing wrong in this Java question until you guarantee that id is always positive. This Java question becomes tricky when you can't guaranteed that id is positive or negative. tricky part is, If id becomes negative than subtraction may overflow and produce incorrect result. 

How do you ensure that N thread can access N resources without deadlock
If you are not well versed in writing multi-threading code then this is real tricky question for you. This Java question can be tricky even for experienced and senior programmer, who are not really exposed to deadlock and race conditions. Key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. 

What is difference between CyclicBarrier and CountDownLatch in Java
Relatively newer Java tricky question, only been introduced form Java 5. Main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for more differences.

What is difference between StringBuffer and StringBuilder in Java ?
Classic Java questions which some people think tricky and some consider very easy. StringBuilder in Java was introduced in JDK 1.5 and only difference between both of them is that StringBuffer methods e.g. length(), capacity() or append() are synchronized while corresponding methods in StringBuilder are not-synchronized. Because of this fundamental difference, concatenation of String using StringBuilder is faster than StringBuffer. Actually its considered bad practice to use StringBuffer any more, because in almost 99% scenario, you perform string concatenation on same thread. See StringBuilder vs StringBuffer for more differences.

Can you access non static variable in static context?
Another tricky Java question from Java fundamentals. No you can not access non-static variable from static context in Java. If you try, it will give compile time error. This is actually a common problem beginners in Java face, when they try to access instance variable inside main method. Because main is static in Java, and instance variables are non-static, you can not access instance variable inside main.

Thursday, 31 July 2014

AndEngine Tutorials

Leave a Comment
1. Getting Started:

2. Entities:
  • Sprites.
  • Tiled Sprites and Animated Sprites.
  • Removing Entities.
  • Using Entities as a Layers.
  • Entity Modifiers.
  • Creating Background.
  • Handling touch events.
  • Scenes.
  • HUD.
  • Creating Menu Scene. 
  • Scenes management. 
  • Handling collisions between entities. 
  • How to create Text properly.

3. Handling Touch Events: 

  • Using Scene touch listener. 
  • Creating left/right game controller buttons. 
  • Handling native Android key events. 
  • Catching Continuous Touch. 
  • Catching Long Click. 

4. Basic Stuff:

  • "Hello World" - basic example.
  • Loading game resources (graphics, fonts and sounds) 
  • Sound and Music.
  • How to design your game? Useful concept 'pattern'.
  • Splash Screen - easy way + code template.
  • Chasing Camera.
  • Setting Camera bounds.
  • Moving Camera smoothly (from point A to B)
  • FPS Counters.
  • Handling onResume, onPause and onDestroy.

5. Physics:

  • Creating Physics World.
  • Differences between body types.
  • Creating Bodies.
  • Handling Collisions between bodies.
  • Removing Body completely.
  • Physics Debug Renderer.
  • Irregular Body Shapes.
  • Creating Sensors.
  • How to overcome gravity forces. 
  • Destroying physics world and all physics objects. 
  • Joints - introduction.
  • Revolute Joint. 
  • Distance joint. 
  • Prismatic joint. 
  • Weeld joint. 
  • Wheel joint.
  • Rope joint. 

6. Game Features:

  • Creating "coin"
  • Handling Jump Feature.
  • Creating Flying Enemy.
  • Creating Zone/Area.

7. Misc - useful:

  • Get cheap domains & web hosting (vouchers!)
  • Super fast emulator - record promo video easily! 
  • Data Storage.
  • SVG Extension - advantages & disadvantages.
  • What device should I buy?
  • Tips and tricks - how to improve performance.
  • Texture Packer - how to use. 
  • Texture Packer - load ITiledTextureRegion. 
  • Texture Packer - Get ride of Sprite Artifacts.
  • Dithering - improve gradient quality. 
  • Reduce memory usage with dithering. 
  • How to restart scene/level. NEW!

Wednesday, 23 July 2014

How can include external jar on Netbeans project

Leave a Comment
Hello friends today i am telling you how to include external jar into your Netbeans project.
One of my friend ask me a question :
When I run "clean and build" the .jar file that is being created only runs if the lib folder is at the same folder of the .jar file.
So if I move the jar file to the desktop and leave the lib folder in the dist folder, the jar file will give me an exception.
How can I deal with this problem?
How can include external jar on Netbeans project,include external jar on Netbeans project,external jar on Netbeans project,jar on Netbeans project,Netbeans project,

I solved this by creating just one jar file with all libraries inside, adding the following to my build.xml file in NetBeans:
<target name="-post-jar">
  <jar jarfile="dist/Combined-dist.jar">
    <zipfileset src="${dist.jar}" excludes="META-INF/*" />
    <zipfileset src="lib/commons-io-1.4.jar" excludes="META-INF/*" />
    <zipfileset src="lib/ninja-utils-3.2.jar" excludes="META-INF/*" />
    <zipfileset src="lib/unicorn-1.0.jar" excludes="META-INF/*" />
        <attribute name="Main-Class" value="com.example.mypackage.Main"/>

This creates a jar file (Combined-dist.jar) which is the combination of the dist jar and the specified library jars (in this case, commons-io-1.4.jar,ninja-utils-3.2.jar and unicorn-1.0.jar). You have to be sure to specify your Main Class package for the new jar file or it won't run when you try to open it.