I have the following code:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
public class FileConnection extends MIDlet implements CommandListener, Runnable {
private Command exit, start;
private Display display;
private Form form;
public FileConnection ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
start = new Command("Start", Command.EXIT, 1);
form = new Form("Write To File");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp() throws MIDletStateChangeException
{
display.setCurrent(form);
}
public void run(){
try{
javax.microedition.io.file.FileConnection filecon =
(javax.microedition.io.file.FileConnection)
Connector.open("file:///root1/photos/fisier.txt", Connector.WRITE);
OutputStream out = filecon.openOutputStream();
PrintStream output = new PrintStream( out );
output.println( "This is a test." );
out.close();
filecon.close();
Alert alert = new Alert("Completed", "Data Written", null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
catch( ConnectionNotFoundException error )
{
Alert alert = new Alert(
"Error", "Cannot access file.", null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
catch( IOException error )
{
Alert alert = new Alert("Error", error.toString(), null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(false);
notifyDestroyed();
}
else if (command == start)
{
new Thread(this).start();
}
}
}
As you can see, I'm trying to write something in a text file, from an emulator. I run that code in a separate thread, to avoid that warning at the runtime. I have in C:\Program Files\WTK2.5.2_01\j2mewtk_template\appdb\DefaultColorPhone\filesystem\root1\photos a file named fisier.txt. When I try to run this code, and press 'Start', I hit 'Yes' at the question 'J2ME... Midlet Suite wants to write the local file system. It's OK to update your files? YES/NO'. And I got on the screen java.io.IOException:, and nothing more!..
What's wrong? Why I got that error? I did not find anywhere a working code, of how to write to a local .txt file.
Don't know what's wrong in my code?
Could be anything from getting the path wrong (and the file not existing), to you not having write access to it, to it being open elsewhere.
Have you tried calling some of the methods the FileConnection class offers, such as canWrite(), exists(), and isOpen(), to see if some of these common problems apply in your case?
Related
Is it possible to get the value of phobe in-call volume from java me midlet? Changing of the volume is not necessary.
Thanks.
AFAIK,
It is not possible to access the phone volume. But you can set your application volume or get the application.
Sample code for Controlling the volume of your application :
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Ticker;
import javax.microedition.media.*;
public class VolumeControlDemo extends MIDlet implements CommandListener {
private Display display;
private Command exit,incr,decr;
Form frm;
VolumeControl vc;
int vol;
Player player;
public VolumeControlDemo() {
display = Display.getDisplay(this);
}
public void startApp() {
frm=new Form("VolumeControlDemo Demo");
exit= new Command("Exit",Command.EXIT,1);
decr= new Command("Decrease",Command.EXIT,1);
incr= new Command("Increase",Command.EXIT,1);
frm.addCommand(exit);
frm.addCommand(decr);
frm.addCommand(incr);
frm.setCommandListener(this);
display.setCurrent(frm);
try {
// Creating player object
player = Manager.createPlayer("/demo.wav");
// Setting loop count
player.setLoopCount(-1);
// Start sound
player.start();
Control cs[];
// Getting Controls object
cs = player.getControls();
for (int i = 0; i < cs.length; i++) {
if (cs[i] instanceof VolumeControl)
// Getting volume control
vc=(VolumeControl)cs[i];
}
} catch (Exception e) {}
}
public void pauseApp() {
}
public void destroyApp(boolean un) {
}
public void commandAction(Command cmd,Displayable d) {
try {
if(decr) {
if(vol>0) vol--;
vc.setLevel(vol);
} else if() {
if(vol<99) vol--;
vc.setLevel(vol);
}
frm.appent("vol="+vc.getLevel());
}catch(Exception e){}
}
}
I am creating simple midlet for Bluetooth communication with server but I can't get it to work on my phone, when I Try to run it in Eclipse/Emulator everything works fine, but on the phone I get "Cannot create MIDlet instance: java.lang.ClassNotFoundException"
I saw somewhere that this exception is mostly path related, but I don't have any external jars or multiple packages.
Here is the code:
package j2meclient;
import java.io.OutputStream;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class J2MEClientMidlet extends MIDlet implements CommandListener,
Runnable {
Display d;
Command cmExit, cmConnect;
Form f;
Thread t;
String connString;
public J2MEClientMidlet() {
f = new Form("Client");
cmExit = new Command("Exit", Command.EXIT, 1);
cmConnect = new Command("Connect", Command.ITEM, 2);
f.addCommand(cmExit);
f.addCommand(cmConnect);
f.setCommandListener(this);
}
public void startApp() {
if (d == null) {
d = Display.getDisplay(this);
d.setCurrent(f);
t = new Thread(this);
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == cmExit) {
destroyApp(false);
notifyDestroyed();
}
if (c == cmConnect) {
t.start();
}
}
public void run() {
try {
LocalDevice local = LocalDevice.getLocalDevice();
DiscoveryAgent agent = local.getDiscoveryAgent();
connString = agent.selectService(new UUID(
"86b4d249fb8844d6a756ec265dd1f6a3", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
} catch (Exception e) {
}
if (connString != null) {
try {
StreamConnection conn = (StreamConnection) Connector
.open(connString);
OutputStream out = conn.openOutputStream();
Thread.sleep(2000);
out.write("Hello, World".getBytes());
out.close();
conn.close();
f.append("Message sent correctly");
} catch (Exception ex) {
f.append("IOException: ");
f.append(ex.getMessage());
}
} else {
f.append("Unable to locate service");
}
}
}
JAD;
MIDlet-1: J2MEClient,,J2MEClient
MIDlet-Jar-Size: 2254
MIDlet-Jar-URL: BTClient.jar
MIDlet-Name: BTClient Midlet Suite
MIDlet-Vendor: Midlet Suite Vendor
MIDlet-Version: 1.0.0
MicroEdition-Configuration: CLDC-1.1
MicroEdition-Profile: MIDP-2.0
Any ideas why I can't run this on phone?
Your class file for the midlet is named J2MEClientMidlet but on the jad file it is defined as J2MEClient. Midlet class file name must match the definition on jad to run successfully from jad.
How to Implement a MIDlet that gets invoked when a SMS is sent to port 50000?
The code is not working. SMS can't be received on the phone, SMS is sent through the emulator (JAVA Me SDK).
What settings should be done to receive the SMS ?
my code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import javax.microedition.io.PushRegistry;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
/**
* #author bonni
*/
public class Midletsms extends MIDlet implements CommandListener{
protected Display display;
//boolean started=false;
Form form = new Form("Welcome");
Command mCommandQuit;
public void startApp() {
String url = "sms://:50000";
try {
PushRegistry.registerConnection(url,this.getClass().getName(), "*");
// PushRegistry.registerConnection(url,"Midletsms.class", "*");
} catch (IOException ex) {
} catch (ClassNotFoundException ex) {
}
form.append("This midlet gets invoked when message is sent to port:50000");
display = Display.getDisplay(this);
display.setCurrent(form);
mCommandQuit = new Command("Quit", Command.EXIT, 0);
form.addCommand(mCommandQuit);
form.setCommandListener(this);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
// throw new UnsupportedOperationException("Not supported yet.");
String label = c.getLabel();
if(label.equals("Quit"))
{
destroyApp(false);
notifyDestroyed();
}
}
}
Not sure I fully understand the problem. But you need to read about PushRegistry.
So there are two types of push registration, static and dynamic.
The code example you have given uses dynamic registration. You will need to manually invoke this MIDlet at least once in order for the push registration to happen. (Aside: In your example you are doing this in the startApp method, this is a very bad idea! Push registration is a potentially blocking operation, and therefore should not be done in a lifecycle method such as startApp. You should do this in a new thread).
The alternative is static registration, where you include the push information in the jad. The push port will be registered when the MIDlet is installed, without the need to run it.
Finally, you say
sms is sent through the emulator
what does this mean? In order for the app to start you need to send an SMS on the relevant port number from another MIDlet (this could be on the same handset if you want).
I found this code on net from Jimmy's blog and it is perfectly working. You can try it your self,
SMSSender.java
public class SMSSender extends MIDlet implements CommandListener {
private Form formSender = new Form("SMS Sender");
private TextField tfDestination = new TextField("Destination", "", 20, TextField.PHONENUMBER);
private TextField tfPort = new TextField("Port", "50000", 6, TextField.NUMERIC);
private TextField tfMessage = new TextField("Message", "message", 150, TextField.ANY);
private Command cmdSend = new Command("Send", Command.OK, 1);
private Command cmdExit = new Command("Exit", Command.EXIT, 1);
private Display display;
public SMSSender() {
formSender.append(tfDestination);
formSender.append(tfPort);
formSender.append(tfMessage);
formSender.addCommand(cmdSend);
formSender.addCommand(cmdExit);
formSender.setCommandListener(this);
display = Display.getDisplay(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
display.setCurrent(formSender);
}
public void commandAction(Command c, Displayable d) {
if (c==cmdSend) {
SendMessage.execute(tfDestination.getString(), tfPort.getString(), tfMessage.getString());
} else if (c==cmdExit) {
notifyDestroyed();
}
}
}
class SendMessage {
public static void execute(final String destination, final String port, final String message) {
Thread thread = new Thread(new Runnable() {
public void run() {
MessageConnection msgConnection;
try {
msgConnection = (MessageConnection)Connector.open("sms://"+destination+":" + port);
TextMessage textMessage = (TextMessage)msgConnection.newMessage(
MessageConnection.TEXT_MESSAGE);
textMessage.setPayloadText(message);
msgConnection.send(textMessage);
msgConnection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
SMSReceiver.java
public class SMSReceiver extends MIDlet implements CommandListener, MessageListener {
private Form formReceiver = new Form("SMS Receiver");
private TextField tfPort = new TextField("Port", "50000", 6, TextField.NUMERIC);
private Command cmdListen = new Command("Listen", Command.OK, 1);
private Command cmdExit = new Command("Exit", Command.EXIT, 1);
private Display display;
public SMSReceiver() {
formReceiver.append(tfPort);
formReceiver.addCommand(cmdListen);
formReceiver.addCommand(cmdExit);
formReceiver.setCommandListener(this);
display = Display.getDisplay(this);
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
display.setCurrent(formReceiver);
}
public void commandAction(Command c, Displayable d) {
if (c==cmdListen) {
ListenSMS sms = new ListenSMS(tfPort.getString(), this);
sms.start();
formReceiver.removeCommand(cmdListen);
} else if (c==cmdExit) {
notifyDestroyed();
}
}
public void notifyIncomingMessage(MessageConnection conn) {
Message message;
try {
message = conn.receive();
if (message instanceof TextMessage) {
TextMessage tMessage = (TextMessage)message;
formReceiver.append("Message received : "+tMessage.getPayloadText()+"\n");
} else {
formReceiver.append("Unknown Message received\n");
}
} catch (InterruptedIOException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ListenSMS extends Thread {
private MessageConnection msgConnection;
private MessageListener listener;
private String port;
public ListenSMS(String port, MessageListener listener) {
this.port = port;
this.listener = listener;
}
public void run() {
try {
msgConnection = (MessageConnection)Connector.open("sms://:" + port);
msgConnection.setMessageListener(listener);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm trying to make my code neater by using multiple classes for my applications
form options. Currently I keep getting null pointer exceptions when trying to setCurrent.
Here is my main class the error starts in my command listener when I call the other class.
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class CalFrontEnd extends MIDlet implements CommandListener {
private Display display;
private List list = new List("Please Select a Option", List.IMPLICIT);
private List Blist = new List("Please Select a Browsing Option", List.IMPLICIT);
private Command select = new Command("Select", Command.SCREEN, 1);
private Command exit = new Command("Exit", Command.EXIT, 2);
private Command save = new Command("Save,", Command.SCREEN, 2);
private DateField calendar;
Alert alert;
//
//
//
public CalFrontEnd() {
display = Display.getDisplay(this);
list.append("Select Date", null);
list.append("Add Events", null);
list.append("Remove Events", null);
list.append("Browse Events", null);
list.addCommand(select);
list.addCommand(exit);
list.setCommandListener(this);
}
//
//Start Application Method
//
public void startApp() {
display.setCurrent(list);
}
//
//Pause Application Method
//
public void pauseApp() {
}
//
//Destroy Application Method
//
public void destroyApp(boolean unconditional) {
}
//
//Method creates form which contains calendar
//
/*public void selectDate()
{
calendar = new DateField("Date In :", DateField.DATE, TimeZone.getTimeZone("GMT"));
Form cform = new Form("Calendar");
cform.append(calendar);
cform.addCommand(exit);
display.setCurrent(cform);
}*/
//
//Method creates form which contains adding events
//
public void AddEvents()
{
TextBox aeText = new TextBox("Add Event","", 256, 0);
display.setCurrent(aeText);
}
//
//Method creates form which contains removing events
//
public void RemoveEvents()
{
Form reform = new Form("Remove Event");
reform.append(calendar);
display.setCurrent(reform);
}
//
//Method creates form which contains removing events
//
public void BrowseEvents()
{
Blist.append("Monthly", null);
Blist.append("Daily", null);
Blist.addCommand(select);
Blist.addCommand(exit);
Blist.setCommandListener(this);
display.setCurrent(Blist);
}
//
//but it's better practice to make each form a different class extending CommandListener and it's own commandAction. And leave the display public static in MIDlet class
//...
public void commandAction(Command command, Displayable displayable) {
if (displayable == list) {
if (command == List.SELECT_COMMAND) {
switch (list.getSelectedIndex()) {
case 0: // select date
SelectDate.BuildCalendar(); //Error Here
break;
case 1: //add events
AddEvents();
break;
}
} else if (command == exit) {
destroyApp(false);
notifyDestroyed();
}
}
}
}
And here is the class that is being called.
public class SelectDate
{
private static DateField calendar;
private static Form form = new Form("derb");
private static Command select = new Command("Select", Command.SCREEN, 1);
private static Command exit = new Command("Exit", Command.EXIT, 2);
private static Command save = new Command("Save,", Command.SCREEN, 2);
private static Display display;
public static void BuildCalendar()
{
calendar = new DateField("Date In :", DateField.DATE, TimeZone.getTimeZone("GMT"));
form.append(calendar);
form.addCommand(exit);
display.setCurrent(form);
}
}
The NullPointerException happens because display in SelectDate class is null.
To fix that, you can for example drop it from there and instead, add to method parameters:
// ...
public static void BuildCalendar(Display display) // added parameter
Then, when you invoke above method from CalFrontEnd, pass the instance of display there:
// ...
SelectDate.BuildCalendar(display); //Error will go away
I am developing a j2me application where there is one parent midlet which calls other java programs. Parent midlet is of implicit list which contains 4 elements. On clicking any of the elements an appropriate java program is called. Everything is working fine, but i don't understand how to show parent midlet from java program on clicking of back button.
Please provide examples.
this is my parent midlet code
package hello;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class Contacts extends MIDlet implements CommandListener,Runnable {
Display display=null;
private Form form=new Form("Contacts");
private List menu=new List("Contact Menu",Choice.IMPLICIT);
private Command exit = new Command("Exit", Command.EXIT, 2);
private Command ok=new Command("Ok",Command.SCREEN,1);
private Command back = new Command("Back", Command.BACK, 1);
private Alert alert;
public Contacts()
{
display = Display.getDisplay(this);
try{
menu.append("Add Contact", Image.createImage("/contact_new.png"));
menu.append("Delete Contact",Image.createImage("/delete-icon.png"));
menu.append("Get Contact",Image.createImage("/document-edit.png"));
menu.append("View Contacts",Image.createImage("/view.png"));
menu.addCommand(ok);
menu.addCommand(exit);
menu.setCommandListener(this);
}
catch(IOException ie)
{
}
}
public void startApp() {
display.setCurrent(menu);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command command, Displayable displayable) {
if (command == exit) {
destroyApp(true);
notifyDestroyed();
return;
}
switch (menu.getSelectedIndex ()) {
case 0:
new ac (this);//call to java program
break;
case 1:
new dc (this);
break;
case 2:
new gc(this);
break;
case 3:
new vc(this);
break;
default:
System.err.println ("Unexpected choice...");
break;
}
}
}
I don't know any API in standard J2ME to interact between MIDlets. At least that is already released. There is some Nokia private API to do some such kind of operations.