solution an error in receive sms - java-me

When send sms from a device to another sometime it received in both devices.
I don't find any error in source code.
Please help me.
NOTE:
this is send source code:
try {
String addr = "sms://" + txt_number.getString()+":1234";
MessageConnection conn = (MessageConnection) Connector.open(addr);
TextMessage msg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(txtSMS.getString());
conn.send(msg);
conn.close();
} catch (IOException ex) { ex.printStackTrace(); }
<blink>and this is receive opretion .this opration support by a thread <blink>
public void run() {
String addr="sms://:1234";
Message msg=null;
try {
conn = (MessageConnection) Connector.open(addr);
while(true)
{
msg=conn.receive();
String mSenderAddress = msg.getAddress();
if (msg instanceof TextMessage) {
String msgTReceived = ((TextMessage)msg).getPayloadText();
Analize_TEXT_message(mSenderAddress,msgTReceived);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

Remove the port number when sending the SMS.

String addr = "sms://" + txt_number.getString()+":1234";
should be
String addr = "sms://" + txt_number.getString()+1234;
port number should be without any quotes.

Related

bluetooth communication server client stuck j2me

How can I use the same Stream to read/write from server to client or from client to server more than once?
I am making a turn based game over bluetooth. Any ideas on how to achieve this in j2me?
I am using RfCOM protocol.
The client code is
public void serviceSearchCompleted(int transID, int respCode) {
try {
StreamConnection SC = (StreamConnection) Connector.open(connectionURL);
input = SC.openDataInputStream();
output = SC.openDataOutputStream();
} catch (IOException ex) {
ex.printStackTrace();
}
while (true) {
f.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c.getLabel().toString().equalsIgnoreCase("send")) {
try {
output.writeUTF("Hey server");
output.flush();
String msg = input.readUTF();
System.out.println(msg);
} catch (IOException ex) {
ex.printStackTrace();
System.out.println("am here now " + ex);
}
}
}
});
synchronized (lock) {
lock.notify();
}
}
}
Server code:
while (true) {
StreamConnection sc = scn.acceptAndOpen();
RemoteDevice rd = RemoteDevice.getRemoteDevice(sc);
DataInputStream input = sc.openDataInputStream();
DataOutputStream output = sc.openDataOutputStream();
String inMsg = input.readUTF();
System.out.println(inMsg + " recived at " + new Date().toString());
output.writeUTF("Hey client Sent at " + new Date().toString());
output.flush();
}
The stream works only once, then nothing happens when I click send again
Processing CONN_INIT 4
Processing CONN_OPEN 4
Processing CONN_SEND 4
Processing CONN_RECEIVE 4
Hey client Sent at Sun Jul 22 19:47:15 GMT+02:00 2012
Processing CONN_SEND 4
Processing CONN_RECEIVE 4
L2CAPConnectionNotifier.acceptAndOpen will block the loop and wait a new connection.
Move your code from the while body to a new thread.
while (true) {
StreamConnection sc = scn.acceptAndOpen();
final RemoteDevice rd = RemoteDevice.getRemoteDevice(sc);
new Thread() {
public void run() {
treatConnection(rd);
}
}.start();
}
private void treatConnection(RemoteDevice rd) {
DataInputStream input = sc.openDataInputStream();
DataOutputStream output = sc.openDataOutputStream();
String inMsg = input.readUTF();
while (inMsg != null) { // not sure about this stop condition...
System.out.println(inMsg + " recived at " + new Date().toString());
output.writeUTF("Hey client Sent at " + new Date().toString());
output.flush();
inMsg = input.readUTF();
}
}

Download Images in loop java me

In my application we have to download around 10 Images from server and display it in mobile. How can I do this? Can I use same HttpConnection for full download? Is any other way for download?
You can do with this simple loop (Supposing imageList is a List with the url of the images).
HttpConnection = null;
Image image = null;
for (int i = 0; i < imageList.getSize(); i++) {
try{
String urlImage = imageList.get(i);
hc = (HttpConnection) Connector.open(urlImage);
image = Image.createImage(hc.openInputStream()));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
hc.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You can try following method in a loop for downloading images from server.
private void downloadImage ( String URL )
{
try
{
System.out.println("URL FOR POST_DATA : "+URL);
// Open up a http connection with the Web server for both send and receive operations
httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE);
// Set the request method to POST
httpConnection.setRequestMethod(HttpConnection.POST);
// Set the request headers
httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action);
httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName);
if(eventName==null || eventName.equals(""))
eventName="default";
httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName);
httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID);
// all the headers are sending now and connection chanel is establising
dis = httpConnection.openDataInputStream();
int ch = 0;
ByteArrayOutputStream bytearray = new ByteArrayOutputStream(250000);
while((ch = dis.read()) != -1)
bytearray.write(ch);
// fileByte contains whole file in bytes
byte fileByte[] = bytearray.toByteArray();
fileSize = fileByte.length;
System.out.println("Got file size : "+fileSize);
if(bytearray!=null) bytearray.close();
midlet.getLastPostedImageResponse(fileByte);
}
catch (IOException ioe)
{
ioe.printStackTrace();
System.out.println("IOException occured during getting last image data : "+ioe.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Eeception occurred during getting last image data : "+e.getMessage());
}
finally
{
System.out.println("Calling close from Last image posted Action");
close();
}

How to post data to server in J2ME? Getting response from server Invalid API Key

I am posting some data to server but i am getting {"status":false,"error":"Invalid API Key."} response from server. My API Key is correct but where is the problem i don't know. Please friends help me. I tried lot but i did not find solution. I have used following code for posting data to server.
public void tryingOne(String dtl){
HttpConnection httpConn = null;
InputStream is = null;
OutputStream os = null;
String url="http://api.geanly.in/ma/index?API-Key="+apikey;
String details = "&orderInfo={\"booking\":{\"restaurantinfo\":{\"id\":\"5722\"},\"referrer\":{\"id\": \"9448476530\" }, \"bookingdetails\":{\"instructions\":\"Make the stuff spicy\",\"bookingtime\": \"2011-11-09 12:12 pm\", \"num_guests\": \"5\"}, \"customerinfo\":{\"name\":\"Vinodh SS\", \"mobile\":\"9345245530\", \"email\": \"vind#gmail.com\", \"landline\":{ \"number\":\"0908998393\",\"ext\":\"456\"}}}}";
try {
System.out.println("url####"+url);
httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
DataOutputStream outStream = new DataOutputStream(httpConn.openDataOutputStream());
outStream.write(details.getBytes(),0,details.length());
outStream.flush();
outStream.close();
//Reading Resp. from server
StringBuffer sb = new StringBuffer();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1) {
sb.append((char) chr);
}
System.out.println("Response from srvr " + sb.toString());
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (httpConn != null) {
try {
httpConn.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Please help me friends...
Thanks
you need to trim the variable "apikey".
I was getting same problem when connecting with Picasa Server.
For sending data using HttpConnection use the class in this tutorial. It also gets the response from the server.

How do I send a message to a bluetooth device?

Using the bluetooth API in j2me, I want to send a message to another mobile phone. I have been able to discover devices and services on the corresponding devices. I have also been able to connect to the services however when I try to send a message from the server to the client. The message is written but the client does not seem to receive it ..
public void startServer() throws IOException {
UUID uuid = new UUID("1101", false);
//Create the service url
String connectionString = "btspp://localhost:" + uuid + ";name=xyz";
//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));
Survey.setTitle(dev.getFriendlyName(true));
//read string from spp client
try {
DataInputStream in = connection.openDataInputStream();
OutputStream writer=connection.openDataOutputStream();
String str="";
TextField textfield;
for (int i=0;i<questions.size();i++){
textfield = (TextField) questions.elementAt(i);
str += formatSurvey(textfield,i)+"&";
}
writer.write(str.getBytes(), 0, str.getBytes().length);
writer.flush();
System.out.println("Written to client "+str);
System.out.println("Reading "+in.readUTF());
try {
displaySurveyresults(str);
}
catch(Exception e){
System.out.println(e.getMessage());
}
streamConnNotifier.close();
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
switchDisplayable(null , getList1());
list1.append(servRecord.toString(), null);
System.out.println("Service discovered..."+servRecord.toString());
for (int i=0;i<servRecord.length;i++){
try {
System.out.println("Test1");
//StreamConnection con = (StreamConnection) Connector.open(servRecord[i].getConnectionURL(0 , false));
String connURL = servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
// Open connection
StreamConnection con = (StreamConnection) Connector.open(connURL);
System.out.println("Test2");
DataInputStream in = con.openDataInputStream();
System.out.println("Test3"+in.readUTF());
//con.openDataOutputStream().write(142);
System.out.println("Test4 "+in.available());
byte[] bte=new byte[in.available()];
System.out.println("Test5 "+bte.length);
in.read(bte);
System.out.println("Test6");
for (int l=0;l<bte.length;l++){
System.out.println(bte[i]);
System.out.println("Test7");
stringItem.setText(stringItem.getText()+1 + bte[i]);
}
OutputStream outStream=con.openOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(outStream);
writer.write("Vimal");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
have I erred somewhere bcause these are codes from the Net?
Try replacing new UUID("1101", false); with new UUID(0x1101);.

Problem using J2ME WMA to send/receive SMS

I'm using WMADemo of the JavaME SDK 3.0 and it's working fine in simulator.
When I install the application in a mobile device it doesn't work. I tried both port 0 (default SMS) and 50000 (listener) with no success. No exception was thrown.
This is an example that works for me
try {
String dest = "sms://" + yourRecipientNumberString;
MessageConnection mConn = (MessageConnection) Connector.open(dest);
TextMessage sms = (TextMessage) mConn.newMessage(MessageConnection.TEXT_MESSAGE);
sms.setPayloadText(msgText);
mConn.send(sms);
mConn.close();
sent = true;
} catch (IOException ioe) {
ioe.printStackTrace();
sent = false;
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
sent = false;
} catch (SecurityException se) {
se.printStackTrace();
sent = false;
}

Resources