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     }

10 comments:

  1. Hallow brother I am new in Codename one please can you send me the source file of this tutorial. my e-mail is yesayaathumn@rocketmail.com

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. +1 Yes, I needed the source file too. Am learning how to communicate with web server. my email is roylee0704@gmail.com

    ReplyDelete
  4. Unforunately I deleted this project from my hardisk, after a reinstall of my operating system. So, I hope you have patient, I will recreate this project again, and I am going to put it on my file server, from where you will be able to download. But till that, have a look on codenameone's web site, you can find there a downloadable zip file with lots of demo applications: http://codenameone.com

    ReplyDelete
    Replies
    1. Thanks Lehel I will wait, yeah I have check all the demo but none of them have the thing that you did...

      Delete
  5. Here you are :) http://siposlehel.atw.hu download from the codenameone section, 2 project: one for the server and one for codnameone mobile client. In the downloadable example i did not use a database server for a simplest architecture. As a web server i used Apache Tomcat 7.0.34, and both project is written under the Netbeans Ide.

    ReplyDelete
  6. Hallow brother, I face a circumstance that I want to display the response from the servlet in a multi-button. Example the result from servlet is Firstname and Lastname. I want to display the firstname in line1 of the Multibutton and Lastname in line2 of the multibutton.. Please help me how I can archieve this.

    ReplyDelete
  7. Hello brother. Please put your questions on codename one mailing list forum: https://groups.google.com/forum/?fromgroups#!forum/codenameone-discussions Thank you.

    ReplyDelete