Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve null when using webservices in codename one

I was calling a data from the database in php and pass the data to codename one using Webservices. If I point my URL to a JSON file, I was able to fetch my record but when I change it to php and encode the page with JSON, I am getting null.

How can I resolve null result when using Webservices in Codename one?

This is my php code that I was calling in codename one

<?php 
/* require the user as the parameter */
//http://localhost:8080/sample1/webservice1.php?user=1
if(isset($_GET['user']) && intval($_GET['user'])) {
    /*soak in the passed variable or set our own*/
    //$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
    $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is  the default
    //$user_id = intval($_GET['user']); //no default

    /* connect to the db */
    $link = mysql_connect('localhost','root','') or die('Cannot connect to the DB');
    mysql_select_db('test',$link) or die('Cannot select the DB');

    /* grab the posts from the db */
    //$query = "SELECT post_title, guid FROM wp_posts WHERE post_author =     $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
    $query = "SELECT * FROM bugs";
    $result = mysql_query($query,$link) or die('Errant query:  '.$query);

    /* create one master array of the records */
    $posts = array();
    if(mysql_num_rows($result)) {
        while($post = mysql_fetch_assoc($result)) {
            $posts[] = array('respons'=>$post);
        }
    }

    /* output in necessary format */
    if($format == 'json') {
        // header('Content-type: application/json');
        echo json_encode(array('respons'=>$posts));
    }


    /* disconnect from the db */
    @mysql_close($link);
}

This is my Codename one code

private static final String URL = "http://localhost/webpin/webservice1.php?user=1&format=json";
showpix.addActionListener((e)->{
    ConnectionRequest req = new ConnectionRequest() {
        @Override
        protected void handleException(Exception ex) {
            //handle error
        }
    };
    req.setUrl(URL);
    req.setPost(true);
    req.setHttpMethod("GET"); //Change to GET if necessary
    req.setDuplicateSupported(true);
    req.addArgument("user", mypin.getText());
    //req.addArgument("argumentToSendThroughPostOrGet2", "value2");
    NetworkManager.getInstance().addToQueueAndWait(req);

    if (req.getResponseCode() == 200) {
        Map<String, Object> out = new HashMap<>();
        Display.getInstance().invokeAndBlock(() -> {
            JSONParser p = new JSONParser();
            try (InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(req.getResponseData()))) {
                out.putAll(p.parseJSON(r));
            } catch (IOException ex) {
                //handle error
            }
        });
        if (!out.isEmpty()) {
            List<Map<String, Object>> responses = (List<Map<String, Object>>) out.get("respons");
            for (Object response : responses) {
                Map res = (Map) response;
                //Object hk =  res.get("id");
                System.out.println(res.get("id"));
                //if(hk.equals("I was returned")){
                     Dialog.show("ok",res.get("id") + "", "ok", "ok");
                //}
                //System.out.println(res.get("key"));
            }
        } else {
            //handle error
        }
    } else {
        //handle error
    }
    //req.setPost(false);
    NetworkManager.getInstance().addToQueueAndWait(req);   
});

When I debug my code with the solutions provided, I was getting the error code below:

java.lang.IllegalStateException: Request method (post/get) can't be modified once arguments have been assigned to the request
Rendering frame took too long 391 milliseconds
at com.codename1.io.ConnectionRequest.setPost(ConnectionRequest.java:1046)
at com.mycompany.myapp.MyApplication.lambda$start$1(MyApplication.java:293)
at com.codename1.ui.util.EventDispatcher.fireActionEvent(EventDispatcher.java:349)
at com.codename1.ui.Button.fireActionEvent(Button.java:411)
at com.codename1.ui.Button.released(Button.java:442)
at com.codename1.ui.Button.pointerReleased(Button.java:530)
at com.codename1.ui.Form.pointerReleased(Form.java:2623)
at com.codename1.ui.Form.pointerReleased(Form.java:2559)
at com.codename1.ui.Component.pointerReleased(Component.java:3223)
at com.codename1.ui.Display.handleEvent(Display.java:2022)
at com.codename1.ui.Display.edtLoopImpl(Display.java:1067)
at com.codename1.ui.Display.mainEDTLoop(Display.java:996)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

This is the code :

      showpix.addActionListener((e)->{
      ConnectionRequest req = new ConnectionRequest() {
      @Override
      protected void handleException(Exception ex) {
    //handle error
    }
   };
   req.setUrl(DESTINATION_URL);
   req.setPost(true);
   req.setHttpMethod("GET"); //Change to GET if necessary
   req.setDuplicateSupported(true);
   //req.addArgument("user", mypin.getText());

   req.addArgument("user", mypin.getText());
   req.addArgument("format", "json");
   req.setPost(false);
    NetworkManager.getInstance().addToQueueAndWait(req);   

    if (req.getResponseCode() == 200) {
   Map<String, Object> out = new HashMap<>();
   Display.getInstance().invokeAndBlock(() -> {
    JSONParser p = new JSONParser();
      try (InputStreamReader r = new InputStreamReader(new           ByteArrayInputStream(req.getResponseData()))) {
        out.putAll(p.parseJSON(r));
       } catch (IOException ex) {
        //handle error
        }
      });


        if (!out.isEmpty()) {
        List<Map<String, Object>> responses = (List<Map<String, Object>>) out.get("response");
          for (Object response : responses) {
             Map res = (Map) response;

         // Object hk =  res.get("id");
           System.out.println(res.get("id"));
        // if(hk.equals("I was returned")){
    //     Dialog.show("ok",res.get("pin")+ "", "ok", "ok");


  //    }

        System.out.println(res.get("id"));



         }
         } else {
        //handle error
          }
          } else {
            //handle error
           }


               });

Another error code:

WARNING: Apple will no longer accept http URL connections from applications you tried to connect to http://localhost/webpin/webservice1.php?user=1&format=json to learn more check out https://www.codenameone.com/blog/ios-http-urls.html [invokeAndBlock1] 0:0:0,0 - Codename One revisions: 375ed2c938445450f0983f0d18235f61e793a7ee 2004

[invokeAndBlock1] 0:0:0,0 - Expected true for key value while parsing JSON token at row: 1 column: 12 buffer: E
[invokeAndBlock1] 0:0:0,0 - Expected true for key value while parsing JSON token at row: 2 column: 3 buffer: E
[invokeAndBlock1] 0:0:0,0 - Expected true for key value while parsing JSON token at row: 4 column: 12 buffer: Eede
[invokeAndBlock1] 0:0:0,0 - Expected true for key value while parsing JSON token at row: 4 column: 13 buffer: Eede
[invokeAndBlock1] 0:0:0,0 - Exception: java.lang.ArrayIndexOutOfBoundsException - -1
java.lang.ArrayIndexOutOfBoundsException: -1
[invokeAndBlock1] 0:0:0,16 - Exception during JSON parsing at row: 4 column: 33 buffer: EedeeContent-Type
at java.util.ArrayList.elementData(ArrayList.java:418)
at java.util.ArrayList.get(ArrayList.java:431)
at com.codename1.io.JSONParser.isStackHash(JSONParser.java:449)
at com.codename1.io.JSONParser.stringToken(JSONParser.java:527)
at com.codename1.io.JSONParser.parse(JSONParser.java:164)
at com.codename1.io.JSONParser.parseJSON(JSONParser.java:427)
at com.mycompany.myapp.MyApplication.lambda$null$0(MyApplication.java:302)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:103)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:140)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
like image 570
Emmy Avatar asked Oct 29 '22 18:10

Emmy


1 Answers

First thing I noticed is you called NetworkManager.getInstance().addToQueueAndWait(req); twice.

Second thing is, you should change req.setPost(true); to req.setPost(false); if you are using $_GET method in your php.

Thirdly, remove the "?" and everything after from your URL, whatever you want to pass should be added through below:

URL:

private static final String URL = "http://localhost/webpin/webservice1.php";

Arguments:

req.addArgument("format", "json");
req.addArgument("user", mypin.getText());

On php side, run your code in a browser to be sure you don't have errors in your code Be sure to uncomment the header. See below minor changes to your code:

$posts = array();
$row = array();
if(mysql_num_rows($result)) {
    while($post = mysql_fetch_assoc($result)) {
        $posts["response"][] = $post;
    }
    $row = array("respons" => $posts["response"], "code" => 200, "message" => "success");
} else {
    $row = array("code" => 101, "message" => "No data was returned");
}

/* output in necessary format */
if($format == 'json') {
    header('Content-type: application/json');
    echo json_encode($row, JSON_PRETTY_PRINT);
}
like image 67
Diamond Avatar answered Nov 09 '22 12:11

Diamond