RecordControl with platformRequest could they work? - java-me

My goal is to produce an application that dial a phone number then record the conservation.
I have tested this code which record voice and then play it on my 5310 correctly.
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
public class VoiceRecordMidlet extends MIDlet {
private Display display;
public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(new VoiceRecordForm());
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
}
class VoiceRecordForm extends Form implements CommandListener {
private StringItem message;
private StringItem errormessage;
private final Command record, play;
private Player player;
private byte[] recordedAudioArray = null;
public VoiceRecordForm() {
super("Recording Audio");
message = new StringItem("", "Select Record to start recording.");
this.append(message);
errormessage = new StringItem("", "");
this.append(errormessage);
record = new Command("Record", Command.OK, 0);
this.addCommand(record);
play = new Command("Play", Command.BACK, 0);
this.addCommand(play);
this.setCommandListener(this);
}
public void commandAction(Command comm, Displayable disp) {
if (comm == record) {
System.getProperty("audio.encodings");
System.getProperty("supports.audio.capture");
System.getProperty("supports.recording");
t.start();
}
else if (comm == play) {
try {
ByteArrayInputStream recordedInputStream = new ByteArrayInputStream(recordedAudioArray);
Player p2 = Manager.createPlayer(recordedInputStream, "audio/amr");
p2.prefetch();
p2.start();
}
catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
}
}
Thread t = new Thread() {
public void run() {
try {
System.getProperty("audio.encodings");
player = Manager.createPlayer("capture://audio");
player.realize();
RecordControl rc = (RecordControl) player.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
player.start();
message.setText("Recording...");
Thread.sleep(5000);
message.setText("Recording Done!");
rc.commit();
recordedAudioArray = output.toByteArray();
player.close();
} catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
};
};
}
Then I made some changes in my code to record conservations
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
public class VoiceRecordMidlet extends MIDlet {
private Display display;
Form f = new VoiceRecordForm();
public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(f);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
class VoiceRecordForm extends Form implements CommandListener {
private MIDlet m;
private StringItem message;
private StringItem errormessage;
private final Command record, play;
private Player player;
private byte[] recordedAudioArray = null;
private TextField phoneField;
private String n;
public VoiceRecordForm() {
super("Recording Audio");
message = new StringItem("", "Select Record to start recording.");
this.append(message);
errormessage = new StringItem("", "");
this.append(errormessage);
record = new Command("Record", Command.SCREEN, 0);
this.addCommand(record);
play = new Command("Play", Command.BACK, 0);
this.addCommand(play);
this.phoneField =new TextField("number","",20,phoneField.PHONENUMBER);
append(phoneField);
this.setCommandListener(this);
}
public void commandAction(Command comm, Displayable disp) {
if (comm == record) {
System.getProperty("audio.encodings");
System.getProperty("supports.audio.capture");
System.getProperty("supports.recording");
t.start();
try
{
n=phoneField.getString().trim();
platformRequest("tel:"+n);
}
catch(javax.microedition.io.ConnectionNotFoundException e)
{
e.printStackTrace();
}
}
else if (comm == play) {
try {
ByteArrayInputStream recordedInputStream = new ByteArrayInputStream(recordedAudioArray);
Player p2 = Manager.createPlayer(recordedInputStream, "audio/amr");
p2.prefetch();
p2.start();
}
catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
}
}
Thread t = new Thread() {
public void run() {
try {
System.getProperty("audio.encodings");
player = Manager.createPlayer("capture://audio");
player.realize();
RecordControl rc = (RecordControl) player.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
player.start();
message.setText("Recording...");
Thread.sleep(5000);
message.setText("Recording Done!");
rc.commit();
recordedAudioArray = output.toByteArray();
player.close();
} catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
};
};
}}
But when pressing record command following error getted
**Error: javax.microedition.media.MediaException: RecordControl**
Any help please?

Related

MailJava in a new Thread

I try to get emails from csv file and start mailing process. Everything works fine if I do it in the main thread. But if I start a new thread and try to do it threre it gives me NullPointer on this line:
email.sendEmail(readerEmail.myList, mailingSubject, mailingText);
For some reason it cannot get a list of emails.
Full code is here:
package com.company;
import javax.mail.MessagingException;
import javax.swing.*;
import static com.company.MainFormAppearance.mailingSubject;
import static com.company.MainFormAppearance.mailingText;
public class NewThead implements Runnable {
public JTextArea jTextAreaStatus;
public Reader readerEmail;
private boolean doStop = false;
public synchronized void doStop() {
this.doStop = true;
}
private synchronized boolean keepRunning() {
return this.doStop == false;
}
#Override
public void run() {
while (keepRunning()){
Email email = new Email();
try {
email.sendEmail(readerEmail.myList, mailingSubject, mailingText);
} catch (MessagingException e) {
e.printStackTrace();
}
}
jTextAreaStatus.setText("completed");
}
}
Main class:
public class MainFormAppearance {
private JTextArea jTextAreaText;
private JTextArea jTextAreaSubject;
private JTextArea jTextAreaEmail;
private JTextArea jTextAreaStatus;
private JLabel blueLabel;
private JLabel copyRightLabel;
public JButton parceButton;
private JButton mailButton;
private JButton stopButton;
private String FILE_PATH_TEXT = "c:/Users/R2D2/Desktop/Main.txt";
private String FILE_PATH_SUBJECT = "c:/Users/R2D2/Desktop/Subject.txt";
public String CsvEmailsPath = "C:\\Users\\R2D2\\Desktop\\Emailstest.csv";
public String CsvBusinessesPath = "C:\\Users\\R2D2\\Desktop\\Businessestest.csv";
public static String mailingText = null;
public static String mailingSubject = null;
public Reader readerEmail;
public Reader readerBusiness;
public JPanel createContentPanel() {
JPanel totalGui = new JPanel();
totalGui.setLayout(null);
totalGui.setBackground(new Color(72, 209, 204));
jTextAreaText = new JTextArea();
jTextAreaSubject = new JTextArea();
jTextAreaEmail = new JTextArea();
jTextAreaStatus = new JTextArea();
blueLabel = new JLabel("Java Mailing Program");
copyRightLabel = new JLabel("\u00a9" + " Alex B - 2018");
parceButton = new JButton("Upload");
mailButton = new JButton("!Start!");
stopButton = new JButton("Stop");
readerEmail = new Reader();
readerBusiness = new Reader();
NewThead newThead = new NewThead();
Thread thread = new Thread(newThead);
//set program label
copyRightLabel.setLocation(10, 230);
copyRightLabel.setSize(400, 20);
copyRightLabel.setFont(new Font("Courier New", Font.ITALIC, 12));
copyRightLabel.setHorizontalAlignment(SwingConstants.CENTER);
totalGui.add(copyRightLabel);
//set program label
blueLabel.setLocation(10, 10);
blueLabel.setSize(400, 20);
blueLabel.setFont(new Font("Courier New", Font.ITALIC, 15));
blueLabel.setHorizontalAlignment(SwingConstants.CENTER);
totalGui.add(blueLabel);
//set Button 1 and click
parceButton.setLocation(270, 50);
parceButton.setSize(100, 30);
totalGui.add(parceButton);
parceButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//parce data from files to Strings
mailingText = readLineByLineJava8(FILE_PATH_TEXT);
mailingSubject = readLineByLineJava8(FILE_PATH_SUBJECT);
try {
readerEmail.readCsvFile(CsvEmailsPath);
readerBusiness.readCsvFile(CsvBusinessesPath);
} catch (IOException e1) {
e1.printStackTrace();
}
if (isNullOrEmpty(mailingText)) {
jTextAreaText.setText("Text is empty! Check it!!!");
} else {
jTextAreaText.setText("***Text is Ready***");
}
if (isNullOrEmpty(mailingSubject)) {
jTextAreaSubject.setText("Subject is empty! Check it!!!");
} else {
jTextAreaSubject.setText("***Subject is Ready***");
}
}
});
//set Button 2 and click
mailButton.setLocation(270, 100);
mailButton.setSize(100, 30);
totalGui.add(mailButton);
mailButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
thread.start();
}
});
stopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
newThead.doStop();
jTextAreaStatus.setText("Stopped");
}
});
stopButton.setLocation(270, 150);
stopButton.setSize(100, 30);
totalGui.add(stopButton);
jTextAreaText.setLocation(20, 52);
jTextAreaText.setSize(200, 16);
jTextAreaText.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaText.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaText);
jTextAreaSubject.setLocation(20, 82);
jTextAreaSubject.setSize(200, 16);
jTextAreaSubject.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaSubject.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaSubject);
jTextAreaEmail.setLocation(20, 112);
jTextAreaEmail.setSize(200, 16);
jTextAreaEmail.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaEmail.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaEmail);
jTextAreaStatus.setLocation(20, 182);
jTextAreaStatus.setSize(200, 16);
jTextAreaStatus.setFont(new Font("Courier New", Font.ITALIC, 12));
jTextAreaStatus.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
totalGui.add(jTextAreaStatus);
totalGui.setOpaque(true);
return totalGui;
}
public static boolean isNullOrEmpty(String str) {
if (str != null && !str.isEmpty())
return false;
return true;
}
}
Class that reads emails from csv (should be correct):
package com.company;
import au.com.bytecode.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
public class Reader {
public CSVReader reader;
public LinkedList myList;
public void readCsvFile(String path) throws IOException {
try {
reader = new CSVReader(new FileReader(path));
String[] column;
myList = new LinkedList<>();
LinkedList <String> map;
while ((column = reader.readNext()) != null) {
map = new LinkedList<String>();
map.add(column[0]);
myList.add(String.valueOf(map).replace("[","").replace("]",""));
//myList.add(String.valueOf(map));
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why i do it in another thread? Because I want to have a chance to stopp mailing process by clicking in stop button and killing a new thread.

InstantiationException while getLocation on Nokia device

New to Nokia development. I am trying to write a hello world for get GPS coordinates of my current location. What am I doing wrong here ?
public class HomeScreen extends MIDlet {
public HomeScreen() {
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
Displayable current = Display.getDisplay(this).getCurrent() ;
if (current == null) {
UpdateJourney updateJourney = new UpdateJourney(this) ;
Display.getDisplay(this).setCurrent(updateJourney) ;
}
}
}
public class UpdateJourney extends Form implements CommandListener, Runnable {
private LocationProvider myLocation;
private Criteria myCriteria;
private Location myCurrentLocation;
private HomeScreen helloScreen;
private Command exitCommand;
private Thread getLocationThread = new Thread(this);;
public UpdateJourney(HomeScreen helloScreen) {
super("Taxeeta");
StringItem helloText = new StringItem("", "Taxeeta");
super.append(helloText);
this.helloScreen = helloScreen;
getLocationThread.start();
}
public double getMyLatitude() {
return myCurrentLocation.getQualifiedCoordinates().getLatitude();
}
public double getMyLongitude() {
return myCurrentLocation.getQualifiedCoordinates().getLongitude();
}
public void commandAction(Command command, Displayable arg1) {
if (command == exitCommand) {
helloScreen.notifyDestroyed();
}
}
public void run() {
myCriteria = new Criteria();
myCriteria.setHorizontalAccuracy(500);
try {
myLocation = LocationProvider.getInstance(myCriteria);
myCurrentLocation = myLocation.getLocation(60);
} catch (LocationException e) {
e.printStackTrace();
System.out
.println("Error : Unable to initialize location provider");
return;
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Error: Waited enough for location to return");
return;
}
System.out.println("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
exitCommand = new Command("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude(),
Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
}
}
In the application descriptor I had UpdateJourney as the MIDlet, I changed it to HomeScreen and it worked.

Voice or Audio player for .amr file in Java ME

I am working on audio recording in Nokia S40 series mobiles. I am able to record the message, but I am not able to play the recorded audio message.
Can anyone help me how to code for voice player for recorded .amr audio files?
Did any one come across this issue?
Here is my working example of recording and playing sound,
public class VoiceRecordMidlet extends MIDlet {
private Display display;
public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(new VoiceRecordForm());
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
}
class VoiceRecordForm extends Form implements CommandListener {
private StringItem message;
private StringItem errormessage;
private final Command record, play;
private Player player;
private byte[] recordedAudioArray = null;
public VoiceRecordForm() {
super("Recording Audio");
message = new StringItem("", "Select Record to start recording.");
this.append(message);
errormessage = new StringItem("", "");
this.append(errormessage);
record = new Command("Record", Command.OK, 0);
this.addCommand(record);
play = new Command("Play", Command.BACK, 0);
this.addCommand(play);
this.setCommandListener(this);
}
public void commandAction(Command comm, Displayable disp) {
if (comm == record) {
Thread t = new Thread() {
public void run() {
try {
player = Manager.createPlayer("capture://audio");
player.realize();
RecordControl rc = (RecordControl) player.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
player.start();
message.setText("Recording...");
Thread.sleep(5000);
message.setText("Recording Done!");
rc.commit();
recordedAudioArray = output.toByteArray();
player.close();
} catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
}
};
t.start();
}
else if (comm == play) {
try {
ByteArrayInputStream recordedInputStream = new ByteArrayInputStream(recordedAudioArray);
Player p2 = Manager.createPlayer(recordedInputStream, "audio/basic");
p2.prefetch();
p2.start();
} catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
}
}
}

Camera snapshot in J2ME Null Pointer Exception

I've spent long on this but no success yet. In my application to capture image and send to the server, I get NullPointerException below;
java.lang.NullPointerException: 0
at Files.CameraMIDlet.snap(CameraMIDlet.java:120)
at Files.CameraForm.commandAction(CameraForm.java:116)
at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46
at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74
at com.sun.midp.chameleon.layers.SoftButtonLayer.soft2(), bci=173
at com.sun.midp.chameleon.layers.SoftButtonLayer.keyInput(), bci=78
at com.sun.midp.chameleon.CWindow.keyInput(), bci=38
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handleKeyEvent(), bci=17
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=277
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:722)
The errors happen at byte[] image = videoControl.getSnapshot("encoding = jpeg"); in the CameraMIDlet and also at midlet.snap(); in the CameraForm, in the code below.
The code for CameraForm is here:
package Files;
import javax.microedition.media.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.control.*;
import java.io.IOException;
class CameraForm extends Form implements CommandListener {
private final CameraMIDlet midlet;
private final Command exitCommand;
private Command captureCommand = null;
private Command showImageCommand = null;
private Player player = null;
private static VideoControl videoControl = null;
private boolean active = false;
private StringItem messageItem;
public CameraForm(CameraMIDlet midlet) {
super("Camera");
this.midlet = midlet;
messageItem = new StringItem("Message", "start");
append(messageItem);
exitCommand = new Command("EXIT", Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
try {
//creates a new player and set it to realize
player = Manager.createPlayer("capture://video");
player.realize();
//Grap the Video control and set it to the current display
videoControl = (VideoControl) (player.getControl("VideoControl"));
if (videoControl != null) {
append((Item) (videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE, null)));
captureCommand = new Command("CAPTURE", Command.SCREEN, 1);
addCommand(captureCommand);
messageItem.setText("OK");
} else {
messageItem.setText("No video control");
}
} catch (IOException ioe) {
messageItem.setText("IOException: " + ioe.getMessage());
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
} catch (SecurityException se) {
messageItem.setText("Security Exception: " + se.getMessage());
}
}
* the video should be visualized on the sreen
* therefore you have to start the player and set the videoControl visible
synchronized void start() {
if (!active) {
try {
if (player != null) {
player.start();
}
if (videoControl != null) {
videoControl.setVisible(true);
//midlet.snap();
}
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
} catch (SecurityException se) {
messageItem.setText("Security Exception: " + se.getMessage());
}
active = true;
}
}
* to stop the player. First the videoControl has to be set invisible
* than the player can be stopped
synchronized void stop() {
if (active) {
try {
if (videoControl != null) {
videoControl.setVisible(false);
}
if (player != null) {
player.stop();
}
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
}
active = false;
}
}
* on the captureCommand a picture is taken and transmited to the server
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
midlet.cameraFormExit();
} else {
if (c == captureCommand) {
midlet.snap();
}
}
}
}
The code for CameraMIDlet is below:
package Files;
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.microedition.media.control.*;
import java.io.IOException;
import javax.microedition.media.MediaException;
public class CameraMIDlet extends MIDlet {
private CameraForm cameraSave = null;
private DisplayImage displayImage = null;
CameraForm captureThread;
private static VideoControl videoControl;
private StringItem messageItem;
public CameraMIDlet() {
}
/*
* startApp()
* starts the MIDlet and generates cameraSave, displayImage, database
*
**/
public void startApp() {
Displayable current = Display.getDisplay(this).getCurrent();
if (current == null) {
//first call
cameraSave = new CameraForm(this);
displayImage = new DisplayImage(this);
Display.getDisplay(this).setCurrent(cameraSave);
cameraSave.start();
} else {
//returning from pauseApp
if (current == cameraSave) {
cameraSave.start();
}
Display.getDisplay(this).setCurrent(current);
}
}
public void pauseApp() {
if (Display.getDisplay(this).getCurrent() == cameraSave) {
cameraSave.stop();
}
}
public void destroyApp(boolean unconditional) {
if (Display.getDisplay(this).getCurrent() == cameraSave) {
cameraSave.stop();
}
}
private void exitRequested() {
destroyApp(false);
notifyDestroyed();
}
void cameraFormExit() {
exitRequested();
}
/**
* restart the camera again
*
*/
void displayCanvasBack() {
Display.getDisplay(this).setCurrent(cameraSave);
cameraSave.start();
}
/**
* the byte[] of the image should be transmitted to a server
*
**/
void buildHTTPConnection(byte[] byteImage) {
displayImage.setImage(byteImage);
Display.getDisplay(this).setCurrent(displayImage);
HttpConnection hc = null;
OutputStream out = null;
try {
//enode the image data by the Base64 algorithm
String stringImage = Base64.encode(byteImage);
// URL of the Sevlet
String url = new String(
"http://ip-adress:8080/C:/Users/HASENDE/Documents/NetBeansProjects/Mobile/pics");
// Obtain an HTTPConnection
hc = (HttpConnection) Connector.open(url);
// Modifying the headers of the request
hc.setRequestMethod(HttpConnection.POST);
// Obtain the output stream for the HttpConnection
out = hc.openOutputStream();
out.write(stringImage.getBytes());
} catch (IOException ioe) {
StringItem stringItem = new StringItem(null, ioe.toString());
} finally {
try {
if (out != null)
out.close();
if (hc != null)
hc.close();
} catch (IOException ioe) {
}
}
// ** end network
}
/**
* stop the camera, show the captured image and transmit the image to a server
**/
void transmitImage(byte[] image) {
cameraSave.stop();
Display.getDisplay(this).setCurrent(displayImage);
buildHTTPConnection(image);
}
public void snap(){
try {
byte[] image = videoControl.getSnapshot("encoding = jpeg");
transmitImage(image);
messageItem.setText("Ok");
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
}
}
}
By identifying the statement that throws NPE you get 99% close to finding the bug:
byte[] image = videoControl.getSnapshot("encoding = jpeg");
NPE in above statement means videoControl is null. Now if you look at it closer, you may notice that in CameraMIDlet, videoControl is initialized with null and never changes to anything else - that's why you are getting NPE. By the way, from CameraForm code it looks like you intended to use videoControl object that is defined there, didn't you.
Side note. CameraForm seems to be designed to used in multiple threads (there are synchronized modifiers) - if this is the case, you better make sure that videoControl is also obtained from it in a synchronized way. Also in that case, add volatile modifier in definition of active flag:
private volatile boolean active = false; // in CameraForm
For Capturing photo use canvas instead of Form,
Check follwing code for Photo Capture
public class ImageCaptureCanvas extends Canvas {
UrMidlet midlet;
VideoControl videoControl;
Player player;
SnapShotCanvas snap;
private Display display;
public ImageCaptureCanvas(UrMidlet midlet) throws MediaException {
this.midlet = midlet;
this.display = Display.getDisplay(midlet);
this.setFullScreenMode(true);
try {
player = Manager.createPlayer("capture://image");
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
} catch (Exception e) {
dm(e.getClass().getName());
}
videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
try {
videoControl.setDisplayLocation(0,0);
videoControl.setDisplaySize(getWidth(), getHeight());
} catch (MediaException me) {
try {
videoControl.setDisplayFullScreen(true);
} catch (MediaException me2) {
}
}
dm("icc10");
videoControl.setVisible(true);
dm("icc11");
player.start();
this.display.setCurrent(this);
}
public void dm(String message) {
Form form = new Form("Error");
form.append(message);
display.setCurrent(form);
}
public void paint(Graphics g) {
}
protected void keyPressed(int keyCode) {
boolean prv=false;
int actn=getGameAction(keyCode);
switch (keyCode) {
case KEY_NUM5:
prv=true;
Thread t = new Thread() {
public void run() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
snap = new SnapShotCanvas(image);
display.setCurrent(snap);
} catch (Exception e) {
dm(e.getClass().getName() + " " + e.getMessage());
}
}
};
t.start();
break;
}
if(!prv){
switch (actn) {
case Canvas.FIRE:
Thread t1 = new Thread() {
public void run() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
snap = new SnapShotCanvas(image);
display.setCurrent(snap);
} catch (Exception e) {
dm(e.getClass().getName() + " " + e.getMessage());
}
}
};
t1.start();
break;
}
}
}
}
SnapShotCanvas Code here
class SnapShotCanvas extends Canvas {
private Image image;
public SnapShotCanvas(Image image) {
this.image = image;
setFullScreenMode(true);
}
public void paint(Graphics g) {
g.drawImage(image, getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);
}
}

javax.bluetooth.BluetoothExeption: unable to swithc master

i want to write bluetooth base app for send and recive string between two device . i have problem . i send string from device A and device B recive it but when i try to send answer from device B to A i get this notifier :
javax.bluetooth.BluetoothExeption: unable to swithc master
it is becouse this part of code :
StreamConnection conn =(StreamConnection) Connector.open(connString);
now what should i do for slove this probleam ?
thanks
Client class :
import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.*;
class Client implements CommandListener, Runnable {
Display display;
String msg;
Midlet midlet;
Form frm;
Command cmdBack = new Command("Back", Command.BACK, 1);
LocalDevice local = null;
DiscoveryAgent agent = null;
Thread thread;
StreamConnection conn = null;
OutputStream out = null;
public Client(String string, Midlet midlet, Display display) {
this.display = display;
this.midlet = midlet;
this.msg = string;
frm = new Form("Send Form");
frm.addCommand(cmdBack);
frm.setCommandListener(this);
thread = new Thread(this);
thread.start();
display.setCurrent(frm);
}
private void doDiscovery() {
try {
local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
String connString = agent.selectService(new UUID("86b4d249fb8844d6a756ec265dd1f6a3", false), ServiceRecord.NOAUTHENTICATE_NOENCRYPT, true);
if (connString != null) {
try {
conn = (StreamConnection) Connector.open(connString);
} catch (IOException ex) {
frm.append(ex.toString() + "1");
}
try {
out = conn.openOutputStream();
} catch (IOException ex) {
frm.append(ex.toString() + "2");
}
try {
out.write(msg.getBytes());
} catch (IOException ex) {
frm.append(ex.toString() + "3");
}
try {
out.close();
} catch (IOException ex) {
frm.append(ex.toString() + "4");
}
try {
conn.close();
} catch (IOException ex) {
frm.append(ex.toString() + "5");
}
System.out.println("Message sent currectly");
} else {
frm.append("connString == null");
}
} catch (BluetoothStateException ex) {
frm.append(ex.toString() + "6");
}
}
public void commandAction(Command c, Displayable d) {
if (c == cmdBack) {
display.setCurrent(midlet.tb);
}
}
public void run() {
doDiscovery();
}
}
Server Class :
import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import javax.microedition.lcdui.*;
class Server implements Runnable {
Display display;
String msg;
Midlet midlet;
Thread thread;
private boolean endRecive = false;
public Server(Midlet midlet, Display display) {
this.display = display;
this.midlet = midlet;
thread = new Thread(this);
thread.start();
}
private void recive() {
try {
LocalDevice local = LocalDevice.getLocalDevice();
if (!local.setDiscoverable(DiscoveryAgent.GIAC)) {
midlet.tb.setString("Failed to change to the discoverable mode");
return;
}
StreamConnectionNotifier notifier = (StreamConnectionNotifier) Connector.open("btspp://localhost:" + "86b4d249fb8844d6a756ec265dd1f6a3");
StreamConnection conn = notifier.acceptAndOpen();
InputStream in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
midlet.tb.delete(0, midlet.tb.size());
midlet.tb.setString(out.toString());
in.close();
conn.close();
notifier.close();
endRecive = true;
thread.interrupt();
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public void run() {
while (endRecive != true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
recive();
}
}
}
and midlet :
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
public class Midlet extends MIDlet implements CommandListener {
Display display = Display.getDisplay(this);
TextBox tb = new TextBox("Chat", null, 100, TextField.ANY);
Command cmdSend = new Command("Send", Command.OK, 1);
Command cmdRecive = new Command("Recive", Command.OK, 2);
Command cmdClear = new Command("Clear...", Command.OK, 3);
Command cmdExit = new Command("Exit", Command.EXIT, 4);
public void startApp() {
tb.addCommand(cmdSend);
tb.addCommand(cmdRecive);
tb.addCommand(cmdClear);
tb.addCommand(cmdExit);
tb.setCommandListener(this);
display.setCurrent(tb);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) {
destroyApp(true);
} else if (c == cmdClear) {
tb.delete(0, tb.size());
} else if (c == cmdSend && tb.getString().length() > 0) {
new Client(tb.getString(), this, display);
} else if (c == cmdRecive) {
tb.setString("Wait ...");
new Server(this, display);
}
}
}

Resources