Pages

Friday, December 7, 2012

Codename One – accesing java servlets with mobile phones



  Using java, there are lot of ways to access a database server which is not local, is not on your phone. You can have java servlets, webservices, or using for exampe the java server pages(jsp) technology, we can retrieve data from database servers.
Unfortunately Codename One, till now, does not support the webservice wsdl technology, but of course you can have servlets or jsp.
An acceptable arhitecture could be, when from client side Codename One, you achieve a servlet, which servlet connects to the database. For having this method, we have to have, two main java Object in Codename One:
NetworkManager
ConnectionRequest

A simple servlet code, accessing a db server, should look like this:
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
        String ID;
        String answer = "no answer";      
        ID = request.getParameter("Id");
        if (ID!=null) {
            //register driver
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            //get the database connection
            Connection con = DriverManager.getConnection ("jdbc:mysql://localhost/test", "user", "password");
            // Create statement
            Statement stmt = con.createStatement ();
            ResultSet rs = stmt.executeQuery ("select * from test where ID="+ID);
            rs.first();           
            answer=rs.getString("Name");                  
         }
        //this is an answer to the client – Codename one          
        out.print(answer);                        
        } finally {           
            out.close();
        }
    }
So, on client side, from mobile phones with Codename One we may have the following code to access the servlet above(the following proecedure is a button click):

D:\Programming\JavaCodenameOne\CodenameOne_2\src\userclasses\StateMachine.java
39     protected void onMain_ButtonAction(Component c, ActionEvent event) {
40         response = "empty";
41         try {          
42              //the NetworkManager object
43              NetworkManager networkManager = NetworkManager.getInstance();
44              networkManager.start();
45              networkManager.addErrorListener(new ActionListener() {
46              public void actionPerformed(ActionEvent evt) {
47                  NetworkEvent n = (NetworkEvent) evt;
48                  n.getError().printStackTrace();                       
49              }});
50              //ConnectionRequest object  
51              ConnectionRequest request = new ConnectionRequest() {
52                  int chr;
53                  StringBuffer sb = new StringBuffer();                  
54                  protected void readResponse(InputStream input) throws IOException {
55                       //reading the answer                     
56                       while ((chr = input.read()) != -1){
57                             sb.append((char) chr);
58                         }
59                       response = sb.toString();                                          
60                       response = response.trim();
61                  } 
62                  protected void handleException(Exception err) {
63                       //An error occured - show a message:
64              Dialog.show("Yikes!!", "Are you connected to the internet? Check your connection", "Ok", null);
65                  }
66              };
67              request.setUrl("http://localhost:8084/WebServicePhone/start"); //servlet calling
68              request.setPost(false);
69              request.addArgument("Id", "1"); //sending a the parameter Id to the servlet                                 
70              networkManager.addToQueue(request);          
71         } catch (Exception e) {
72             System.out.println(e.getMessage());
73         }               
74         while(response.equals("empty")) {
75             //waiting for the answer from the serlvet or jsp server
76         }
77         //set the label with the information from the server
78         findLabel().setText(response);
79         Dialog.show("Hi World", "Getting Data From JSP - MYSQL database", "OK" ,null);               
80     }