简体   繁体   中英

How to run java Application from Midlet

1st I am new to Java. Whatever i learned is thanks to Netbeans & Internet. I am using NetBeans IDE 7.0.1 jdk1.7.0_25 Java_ME_platform_SDK_3.2

Project 1st- InsrtDB

package insrtdb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class InsrtDB {

private static Statement stmt = null;

    private static Connection con = null;
    public static  String mt="0:00:00";
    public static  String sms="Test InsrtDB";

     /**
     * @param args the command line arguments
     */

    public static void main(String[] args) throws ClassNotFoundException, SQLException, Exception {

     // TODO code application logic here
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     con = DriverManager.getConnection("jdbc:odbc:MADb");
     System.out.println("Connected!");
     stmt = con.createStatement();
     int rowsEffected = 0;

     // Example INSERT new record
     rowsEffected = updateData("INSERT INTO Reqst (myTime,SMS) VALUES (' "+mt+" ',' "+sms+" ')");
     System.out.print("Inserted a Row : ");
     con.close();
    }

     public static int updateData(String SQL) throws Exception {
     return stmt.executeUpdate(SQL);
     }
}

OUTPUT-InsrtDB(run) run: Connected! Inserted a Row : BUILD SUCCESSFUL (total time: 27 seconds)

Project 2nd-SndRecvSMS(MIDlet application)

private class SmsReceiverThread extends Thread {
public void run() {
try {
       //  Receive Message
       TextMessage txtMsg = (TextMessage) receiveCon.receive();

       // Get the receiving SMS phone number
       String senderTpNo = txtMsg.getAddress();

       // Get the receiving SMS message
       String senderMsg = txtMsg.getPayloadText();

      // Create a TextBox and direct the incomming message to that
      switchDisplayable(null, getTxtBox());

      smt = senderMsg.substring(10);
      msgSnt = senderMsg.substring(0, 10);
      stringItem.setText(smt);
      stringItem1.setText(msgSnt);
      } 
      catch (IOException ex) {
      }
  }

}

I ran this this midlet 1st on JavaMEPhone1 & than on JavaMEPhone2 & I can send & receive SMS successfully . Now when in 2nd application I add 1st application in Resources as add project & Clean & Build I get Output:- BUILD SUCCESSFUL (total time: 8 seconds)

Now when I add codes as Highlighted in Bold

private class SmsReceiverThread extends Thread {

public void run() {
try {
     //  Receive Message
     TextMessage txtMsg = (TextMessage) receiveCon.receive();

     // Get the receiving SMS phone number
     String senderTpNo = txtMsg.getAddress();

     // Get the receiving SMS message
     String senderMsg = txtMsg.getPayloadText();

     // Create a TextBox and direct the incomming message to that
     switchDisplayable(null, getTxtBox());

     smt = senderMsg.substring(10);
     msgSnt = senderMsg.substring(0, 10);
     stringItem.setText(smt);
     stringItem1.setText(msgSnt);
     } catch (IOException ex) {
  }

   insrtdb.InsrtDB.mt=smt;
   System.out.println("New value of mt =  "  +insrtdb.InsrtDB.mt);
   insrtdb.InsrtDB.sms=msgSnt;
   System.out.println("New value 0f sms = "  +insrtdb.InsrtDB.sms);
   try {
         insrtdb.InsrtDB.class.getClass().newInstance();
         } catch (IllegalAccessException ex) {
         } catch (InstantiationException ex) {
       }

    }
}

Clean & Build and Run. Output:- For JavaMEPhone1 Running 123456790 012345678917:12:50 run: BUILD SUCCESSFUL (total time: 8 minutes 14 seconds) Output:- For JavaMEPhone2 Message received New value of mt = 17:12:50 New value 0f sms = 0123456789 run-no-build: BUILD SUCCESSFUL (total time: 2 minutes 34 seconds)
But Connected! Inserted a Row lines were missing & in Database Row was not inserted.

What I am missing?

Well I was looking for basic, simple & workable solution. But First & foremost let me give you 2 references. 1st:-How to send and receive SMS in J2ME by anujarosha at http://anujarosha.wordpress.com/2011/07/20/how-to-send-and-receive-sms-in-j2me/ This is thorough & detailed Blog & appreciates the same. 2nd:-Send text message from mobile device to computer-java mobile socket level Programming by Sanjeewa Malalgoda at http://sanjeewamalalgoda.blogspot.in/2009/09/send-text-message-from-mobile-device-to.html This is very simple Blog & its self explanatory & again appreciated the same. These 2 Blogs has inspired me to share my solution with every one on internet. Actually this is a part of Demo I am trying to build & it has 4 steps. First: A mobile midlet application sends SMS to 2nd Mobile. Second: 2nd mobile midlet application receives this SMS (if application is running).This 2nd mobile is connected to Laptop thru USB data cable. Third: And after receiving the SMS, application send a socket to server socket, a java application running on Laptop. Fourth: Server socket on receipt split & insert into database table which has 2 fields one myTime & 2nd SMS. Now I have to deal with three Times. 1st mobiles Time (senders Time), 2nd mob Time (receiving mobile Time) & 3rd Laptop Time & naturally all 3 times are not synchronized. For me, a sender Time is important factor & hence I have to incorporate the same in SMS itself. Again SMS strings length can vary from 0 to 160; hence the same is incorporated in SMS itself. Hence String SMS has 3 parts: String “SMS length”+String”sms”+String “Time” (hh:mm:ss).

My solution is 1st java applicaion as follows

   /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aserver;
import java.net.*; 
import java.io.*; 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
 *
 * @author A S Patel
 */
public class AServer {
private static ServerSocket serverSocketin; 
private static Statement stmt = null;
 private static Connection con = null;
public static  String mt;
 public static  String sms;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
     try  { 
serverSocketin = new ServerSocket(8206); 
 DataRiciver dataRiciver=new DataRiciver(); 
 dataRiciver.start(); 
        }catch (IOException e) { 
        } 
      }

 static class DataRiciver extends Thread { 
        @Override
public void run(){ 
while (true){ 
try { 
                    Socket incoming = serverSocketin.accept(); 
                    DataInputStream in = new DataInputStream(incoming.getInputStream()); 
                    String data=""; 
data = in.readLine(); 
System.out.println(data); 
 String lN=data.substring(0, 3);
                int n=Integer.parseInt(lN);
mt=data.substring(n+3);
sms=data.substring(3, n+3);
InsertDB();
in.close(); 
incoming.close(); 
Thread.sleep(1000); 
                }catch (Exception e) { 
                  } 
        }
} 
    }

    public static void InsertDB() throws ClassNotFoundException, SQLException, Exception{
           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           con = DriverManager.getConnection("jdbc:odbc:MADb");
           System.out.println("Connected!");
           stmt = con.createStatement();
           int rowsEffected = 0;
           // Example INSERT new record
           rowsEffected = updateData("INSERT INTO Reqst (myTime,SMS) VALUES (' "+mt+" ',' "+sms+" ')");
            System.out.print("Inserted a Row : ");
            con.close();
        }
    public static int updateData(String SQL) throws Exception {
        return stmt.executeUpdate(SQL);
     } 
    }

Now 2nd is Midlet code.As in Neatbeans if you use visual Midlet the Flow Diagram will be!

Now in New Message Form select send & right click & select go to source

there add this code

     } else if (command == send) {                                          
                // write pre-action user code here
                 Calendar cal = Calendar.getInstance();
                 int hr = cal.get(Calendar.HOUR_OF_DAY);
                int min = cal.get(Calendar.MINUTE);
                int snd = cal.get(Calendar.SECOND);
                String mt = String.valueOf(hr)+":"+String.valueOf(min)+":"+String.valueOf(snd);
                phnNoStr = phnNoTexField.getString();
                msgStr =  msgTexField.getString() ;
                int n=msgStr.length();
                String lN;
               if(n<10){lN="00"+ String.valueOf(n);}else
                   if(n<100){lN="0"+ String.valueOf(n);}else
                   {lN= String.valueOf(n);}
               mySMS=lN+msgStr+mt;
          // write post-action user code here
new SMSThread(phnNoStr, mySMS).start();
 switchDisplayable(null, getSuccess());
            }                                           

At the end part of code ie after public void destroyApp(boolean unconditional)

you have Regular Inner Class private class SmsReceiverThread extends Thread

add following code there after

                String senderMsg = txtMsg.getPayloadText();


     // Create a TextBox and direct the incomming message to that
                switchDisplayable(null, getTxtBox());
                String lN=senderMsg.substring(0, 3);
                int n=Integer.parseInt(lN);
                 smt = senderMsg.substring(n+3);
                msgSnt = senderMsg.substring(3, n+3);
stringItem.setText(smt);
stringItem1.setText(msgSnt);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                }
           String data=senderMsg;
           sendData(data);
            } catch (IOException ex) {
            }
  switchDisplayable(null, getSplashScreen());
        }
  }    
 public void sendData(String data) { 
try { 
StreamConnection connection = (StreamConnection) Connector.open("socket://localhost:8206"); 
PrintStream output = new PrintStream(connection.openOutputStream()); 
data=data +"\n"; 
output.write(data.getBytes()); 
output.flush(); 
output.close(); 
connection.close();
 } catch (Exception e) { 
        } 

You can run 1st code in Neatbeans Than 2 instances of Midlets

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM