I all.

I am trying to make a program that connects 2 mobile phones, and send a string to the server mobile, and then sends the thread back.
I have tested it in netbeans, and it looks like it discoveres the device. but then I get an error:

Address: 0123456789AF
Name: WirelessToolkit
Starting device inquiry...
Device Inquiry Completed.
Bluetooth Devices:
1. 0000000DECAF (WirelessToolkit)

Searching for service...
java.lang.NullPointerException
at com.sun.kvem.jsr082.bluetooth.DataL2CAPReaderWriter.<init>(DataL2CAPReaderWriter.java:50)
at com.sun.kvem.jsr082.bluetooth.SDPClient$SDPTransport.start(SDPClient.java:283)
at com.sun.kvem.jsr082.bluetooth.SDPClient.openTransport(SDPClient.java:102)
at com.sun.kvem.jsr082.bluetooth.SDPClient.open(SDPClient.java:183)
at com.sun.kvem.jsr082.bluetooth.SDPClient.<init>(SDPClient.java:68)
at com.sun.kvem.jsr082.bluetooth.ServiceSearcher.start(ServiceSearcher.java:76)
at com.sun.kvem.jsr082.bluetooth.DiscoveryAgentImpl.searchServices(DiscoveryAgentImpl.java:225)
at javax.bluetooth.DiscoveryAgent.searchServices(DiscoveryAgent.java:259)
at SampleSPPClient.main(SampleSPPClient.java:96)
at SPP_midlet.listAction(SPP_midlet.java:147)
at SPP_midlet.commandAction(SPP_midlet.java:95)
at javax.microedition.lcdui.List.callKeyPressed(List.java:818)
at javax.microedition.lcdui.Display$DisplayAccessor.keyEvent(Display.java:2209)
at javax.microedition.lcdui.Display$DisplayManagerImpl.keyEvent(Display.java:2952)
at com.sun.midp.lcdui.DefaultEventHandler.keyEvent(DefaultEventHandler.java:249)
at com.sun.midp.lcdui.AutomatedEventHandler.keyEvent(AutomatedEventHandler.java:620)
at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.handleVmEvent(DefaultEventHandler.java:699)
at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(DefaultEventHandler.java:608)

Does anyone know what this means. I can post the code if needed.
Hope someone can help me.

kind regards Michael.

Can you post your code? It will make debugging easier...

Sure. The code for the client is here:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author MMA
 */
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
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;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
 
/**
* A simple SPP client that connects with an SPP server
*/
public class SampleSPPClient implements DiscoveryListener{
    
    //object used for waiting
    private static Object lock=new Object();
    
    //vector containing the devices discovered
    private static Vector vecDevices=new Vector();
    
    private static String connectionURL=null;
 
    public static void main(String[] args) throws IOException {
        
        SampleSPPClient client=new SampleSPPClient();
        
        //display local device address and name
        LocalDevice localDevice = LocalDevice.getLocalDevice();
        System.out.println("Address: "+localDevice.getBluetoothAddress());
        System.out.println("Name: "+localDevice.getFriendlyName());
        
        //find devices
        DiscoveryAgent agent = localDevice.getDiscoveryAgent();
      
        System.out.println("Starting device inquiry...");
        agent.startInquiry(DiscoveryAgent.GIAC, client);
        
        try {
            synchronized(lock){
                lock.wait();
            }
        } 
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        
        System.out.println("Device Inquiry Completed. ");
        
        //print all devices in vecDevices
        int deviceCount=vecDevices.size();
        
        if(deviceCount <= 0){
            System.out.println("No Devices Found .");
            System.exit(0);
        }
        else{
            //print bluetooth device addresses and names in the format [ No. address (name) ]
            System.out.println("Bluetooth Devices: ");
            for (int i = 0; i <deviceCount; i++) {
                RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
                System.out.println((i+1)+". "+remoteDevice.getBluetoothAddress()+" ("+remoteDevice.getFriendlyName(true)+")");
            }
        }
        
/*        System.out.print("Choose Device index: ");
        BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));
        
        String chosenIndex=bReader.readLine();
        int index=Integer.parseInt(chosenIndex.trim());*/
        
        //check for spp service
        RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(0);
        UUID[] uuidSet = new UUID[1];
        uuidSet[0]=new UUID("1101",false);
        
        System.out.println("\nSearching for service...");
        agent.searchServices(null,uuidSet,remoteDevice,client);
        
        try {
            synchronized(lock){
                lock.wait();
            }
        } 
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        if(connectionURL==null){
            System.out.println("Device does not support Simple SPP Service.");
            System.exit(0);
        }
        
        //connect to the server and send a line of text
        StreamConnection streamConnection=(StreamConnection)Connector.open(connectionURL);
        
        //send string
        OutputStream outStream=streamConnection.openOutputStream();
        
            outStream.write(1);
            outStream.flush();            
        
        
        
        
        //read response
        InputStream inStream=streamConnection.openInputStream();
        int input = inStream.read();
/*        BufferedReader bReader2=new BufferedReader(new InputStreamReader(inStream));
        String lineRead=bReader2.readLine();*/
        System.out.println(input);
        
                
    }//main
    
    //methods of DiscoveryListener
    public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
        //add the device to the vector
        if(!vecDevices.contains(btDevice)){
            vecDevices.addElement(btDevice);
        }
    }
 
    //implement this method since services are not being discovered
    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        if(servRecord!=null && servRecord.length>0){
            connectionURL=servRecord[0].getConnectionURL(0,false);
        }
        synchronized(lock){
            lock.notify();
        }
    }
 
    //implement this method since services are not being discovered
    public void serviceSearchCompleted(int transID, int respCode) {
        synchronized(lock){
            lock.notify();
        }
    }
 
    
    public void inquiryCompleted(int discType) {
        synchronized(lock){
            lock.notify();
        }
        
    }//end method
    
    
    
}

server is:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author MMA
 */
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

 
import javax.bluetooth.*;
import javax.microedition.io.*;
 
/**
* Class that implements an SPP Server which accepts single line of
* message from an SPP client and sends a single line of response to the client.
*/
public class SampleSPPServer {
    
    //start server
    private void startServer() throws IOException{
 
        //Create a UUID for SPP
        UUID uuid = new UUID("1101", true);
        //Create the servicve url
        String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server";
        
        //open server url
        StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
        
        //Wait for client connection
        System.out.println("\nServer Started. Waiting for clients to connect...");
        StreamConnection connection=streamConnNotifier.acceptAndOpen();
 
        RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
        System.out.println("Remote device address: "+dev.getBluetoothAddress());
        System.out.println("Remote device name: "+dev.getFriendlyName(true));
        
        //read string from spp client
        InputStream inStream=connection.openInputStream();
        int input = inStream.read();
        /*BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
        String lineRead=bReader.readLine();*/
        System.out.println(input);
        
        //send response to spp client
        OutputStream outStream=connection.openOutputStream();
        outStream.write(input);
   /*     PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
        pWriter.write("Response String from SPP Server\r\n");
        pWriter.flush();
 
        pWriter.close();*/
        
        outStream.flush();
        streamConnNotifier.close();
 
    }
 
 
    public static void main(String[] args) throws IOException {
        
        //display local device address and name
        LocalDevice localDevice = LocalDevice.getLocalDevice();
        System.out.println("Address: "+localDevice.getBluetoothAddress());
        System.out.println("Name: "+localDevice.getFriendlyName());
        
        SampleSPPServer sampleSPPServer=new SampleSPPServer();
        sampleSPPServer.startServer();
        
    }
}

You need to sort the basic. This is supposed to be application for mobile devices. Therefore we do not use main() method but go with MIDlet and its three subclasses startApp(), pauseApp() and destroyApp(). Have look on this example of BT communication from Jonathan Knudsen (download chap 20)

I will look at it. thx for the help so far.

Hi again.

thx for the great program from Jonathan Knudsen. I have a problem though. When i import it, there are a lot of red underlinings in the files, (src folder). The program runs, but it is very hard to find out what is what for me then. Did I import it wrong or do something other wrong. I use netbeans btw. Hope you can help me. Kind regards Michael.

Red underlining means either there is an error or you missing libraries. In your case it is the second option as the program is OK. Do you have Mobility pack installed on your NetBeans?

As for application

  • BlueChewMIDlet provides user interface and coordinate the remaining objects of the application.
  • BlueChewFinder provides device discovery, the list of found devices is stored in Vector
  • BlueChewServer is the service itself.
  • BlueChewService - compact represenatation of ServiceRecord, it holds name, address and connection string
  • Log - keeps track of a list of messages (Jonathan used it for debugging)

thx for the explanation.

I think I have mobility pack installed. I am able to create a project using mobility as project category. The strange thing is that the project compiles without a problem, so that is why I dont understand all the red underlinings.

Do right click on project folder kb-ch20 select Properties from the bottom of the menu. In Properties check platform settings select in Category -> Platform and check if it is pointing to your WTK or is requesting something from outside (correct it if wrong).
Close this dialogue window. Expand project folder view kb-ch20 -> Project Configurations -> Default Configuration -> Resources and delete the pointer to non-existing resource location on D:\ drive (looks like Jonathan had something there and forgot to remove it)

Let me know what it does now...

It is pointing to my sun wireless toolkit 2.5, so that should be ok. Under the default configuration -> resources, there is only resources, so I dont think that it's pointing to anything on the d drive here.

OK this getting interesting as I had to correct WTK and remove resource. What you get when you right click on project folder and select Resolve Reference Problems (second option from bottom if there any reference problems)?

that option is not there. (proporly meaning that there are no reference problem ?).
I could imagine that the error is that I imported it wrong or something. The first line in the code (import java.io.*) has a "!" to the left of it. And I think that it is strange that that line shouldn't work.

Dunno what could cause such thing. OK, in attachments are source files as I have them. They working fine. Just place these files in the project "src" folder to replace what ever you have there and run them. Let me know if you getting any errors etc.

thanks for the files. The folder that I should put them in, is that \projectname\build\compiled\src. I have no files there. I have the 5 files with the same name, but with .class under, \ImportedProject-Kb-ch201\build\compiled.

I have now made a new project, and I have copied the files to the src folder, and it looks like there are no errors (hurraa :) ), but when I try to run it, nothing happens. Is that because I have to make a midlet that activates it or something ?

Right click on project folder -> Properties -> in Category select Application Descriptor -> on right side of the window click on the MIDlets. Here you need to point NetBeans to MIDlet in your project. Click Add and find location of BlueChewMIDlet.java. Compile and run

commented: The Phone Guru +3

Perfect mate. That did the trick. I will have a look at the application now. Thx a lot mate.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.