How to allow null when using web services in a codename

I called the data from the database in php and passed the data to the codename using Webservices. If I point my URL to a JSON file, I was able to get my entry, but when I changed it to php and encoded the page using JSON, I get null.

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

This is my php code that I called in the codename

<?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 code. 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 provided solutions, I get 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:

. Apple HTTP- , http://localhost/webpin/webservice1.php?user=1&format=json, . https://www.codenameone.com/blog/ios-http-urls.html [invokeAndBlock1] 0: 0: 0,0 - Codename : 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)
+4
1

, NetworkManager.getInstance().addToQueueAndWait(req);.

-, req.setPost(true); req.setPost(false);, $_GET php.

-, "?" URL, , , :

URL:

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

:

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

php , , . header. :

$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);
}
+2

Source: https://habr.com/ru/post/1658285/


All Articles