Android Question Json Error : End of input at character 0 of

WebQuest

Active Member
Licensed User
Hi community oh written an app that through a php script receives data from the mysql db on my server. everything worked but since I inserted the 'RealEscape string' method, it didn't work anymore. I removed the 'RealEscape String' function and brought the php script back to the origins and now I get this error:

org.json.JSONException:

at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
at org.json.JSONTokener.nextValue(JSONTokener.java:97)
at anywheresoftware.b4a.objects.collections.JSONParser.NextArray(JSONParser.java:60)
at b4a.example.main._jobdone(main.java:986)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:710)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:339)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:249)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:139)
at anywheresoftware.b4a.BA$2.run(BA.java:360)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)



Json code to receive data:
Sub JobDone(Job As HttpJob)
      
       If Job.Success Then
        Dim res As String
            res = Job.GetString
            Dim parser As JSONParser
            parser.Initialize(res)
        
            Dim List1 As List
            List1.Initialize
            List1 = parser.NextArray 'returns a list with maps
          If List1.Size>0 Then
            For i = 0 To List1.Size - 1
                Dim Root As Map
                Root=CreateMap("Tablet":Tablet,"Nome_Attivita":NomeAttivita,"ID":ID)
                Root=List1.Get(i)
              
                ListaServer.ID=Root.Get("ID")
                ListaServer.Tablet=Root.Get("Tablet")
                ListaServer.NomeAttivita=Root.Get("Nome_Attivita")
              
                ListAttvita.Add("/ ID :"&Root.Get("ID")&"="&Root.Get("Nome_Attivita")&"-"&Root.Get("Tablet"))
                Log(ListAttvita.Get(i))
            Next
          
            For i = 0 To ListAttvita.Size - 1
                SpinnerActivity.Add(ListAttvita.Get(i))
            Next
          
          Else
              ToastMessageShow("Non ci sono Attività aggiunte!",True) 
         End If
        Else
            Log(Job.ErrorMessage)
            ToastMessageShow("Error: " & Job.ErrorMessage, True)
        End If
  
  
    Job.Release
  
End Sub

B4X:
public Sub GetActivity
    ExecuteRemoteQuery("SELECT Tablet,ID,Nome_Attivita FROM Service_Team","")
End Sub

Sub ExecuteRemoteQuery(Query As String, JobName As String)
    Dim job As HttpJob
    job.Initialize(JobName, Me)
    job.PostString("https://www.xxxxxxx.com/Client/ScriptAdd_UserServer.php", Query)
End Sub

php code, file present on the server.:
<?php

$databasehost = "localhost";
$databasename = "namedb"; //hidden data
$databaseusername ="nameuser"; //hidden data
$databasepassword = "passwordDB"; //hidden data


$con = mysqli_connect($databasehost,$databaseusername,$databasepassword, $databasename) or die(mysqli_error($con));

mysqli_set_charset ($con , "utf8");
$query = file_get_contents("php://input");
$sth = mysqli_query($con, $query);

if (mysqli_errno($con))
{
   header("HTTP/1.1 500 Internal Server Error");
   echo $query.'\n';
   echo mysqli_error($con);
}
else
{
   $rows = array();
   while($r = mysqli_fetch_assoc($sth))
   {
     $rows[] = $r;
   }
   $res = json_encode($rows,True);
    echo $res;
    mysqli_free_result($sth);
}
mysqli_close($con);

?>
 
Last edited:

drgottjr

Expert
Licensed User
Longtime User
something doesn't sound right. if the app worked before, and you have "brought the php script back to the origins", and it no longer works, then you haven't brought the php script back to the origins. do you not have a backup of the origins? clearly, something is still not in the original form. what else did you change?

this is not crucial, but somebody (if not me) will mention to you that
B4X:
Sub JobDone()
is not used anymore.
B4X:
Wait For
is used.
https://www.b4x.com/android/forum/threads/b4x-okhttputils2-with-wait-for.79345/

you should use try/catch around those jsonparser methods. eg:
B4X:
   try
            List1 = parser.NextArray 'returns a list with maps
   catch
            log ("next array failed: " & lastexception.message)
   end try

anything coming in from the outside should be trapped for the unexpected. you're expecting an array, but that may not be what's there. when you call your res = job.getstring, you might want to print res to the log to see what you're actually receiving. i realize you test for job.success, but that doesn't mean what was received was what was expected.

we've see a similar problem before, but it's unclear at present if your issue is the same. you need to identify what you're actually downloading. and you should find out what happened to your original app. the only way your original app could no longer work is 1) you no longer have the original or 2) the php script has changed. something is no longer what it was.
 
Upvote 0

WebQuest

Active Member
Licensed User
Thanks for the reply, I double-checked the php script and now I can read and receive data again. Now the problem comes out in the post method and as in the previous example it worked and now no, I checked the script in the server errorlog I don't receive any error only in b4a I receive this error:

java.io.FileNotFoundException: /data/user/0/b4a.example/cache/2 (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:231)
at java.io.FileInputStream.<init>(FileInputStream.java:165)
at anywheresoftware.b4a.objects.streams.File.OpenInput(File.java:212)
at b4a.example.httpjob._getstring2(httpjob.java:399)
at b4a.example.httpjob._getstring(httpjob.java:105)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:710)
more.......

and this line shows me in http:

tr.Initialize2(File.OpenInput(HttpUtils2Service.TempFolder, taskId), Encoding)

andi in FttpUtils2Service this line :

TaskIdToJob.Initialize


i am using this code:

B4a:
Sub  Post_String(JsonString As String) As ResumableSub
    Dim j As HttpJob
    j.Initialize("", Me)
    j.PostString(Servername & ScriptScriviNelDB, JsonString)
    Wait For (j) JobDone(j As HttpJob)
    Log(j.GetString)
    Dim Result As String = j.GetString
    j.Release
    Return Result
End Sub

Sub BTInsert_Click
    Dim Post As String = EditText1.Text
    Dim JsonRow_Connection As Map = CreateMap("username":"xxxxxxxxx","dbname":"xxxxxxxxx","password":"xxxxxxxxx","Post":Post)
    JsonGenerator.Initialize(JsonRow_Connection)
    Dim JSONstring As String = JsonGenerator.ToString
    
    Wait For(Post_String(JSONstring)) Complete (Result As String)
    Log(Result)
    ToastMessageShow("post aggiunto al db!",True)

End Sub

PHP:
<?php

$json = file_get_contents("php://input");
$jsone = array();
$jsone=json_decode($json, true);

$servername = "localhost";
$username = $jsone["username"];
$password = $jsone["password"];
$dbname = $jsone["dbname"];

$Post=$jsone["Post"];



// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

  mysqli_select_db($conn,$dbname) or die(mysqli_error());
  mysqli_query($conn,"SET CHARACTER SET utf8");
  mysqli_query($conn,"SET NAMES 'utf8'");
    
if (mysqli_error($conn))
{
    echo "Failed to connect to MySQL: " . mysqli_error();
}

// Check connection
if (!$conn)
{
    die("Connection failed: " . mysqli_connect_error());
}
else
{
 
 $sql = "INSERT INTO Tabella1 (Post) VALUES('$Post')"

if (mysqli_query($conn, $sql))
{
    echo "Key Active successfully";
}
    else
{
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);

}

?>
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
You are logging/accessing j.GetString without any regards to j.Success. You should never access j.GetString without j.Success equaling to True.
 
Upvote 0

WebQuest

Active Member
Licensed User
right I added the j.success, it does not release errors but the dialogue always returns 'null'. maybe I'm wrong on the map?
 
Upvote 0

WebQuest

Active Member
Licensed User
from the PHP: NET manual I found this 'json_decode', returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
 
Upvote 0

drgottjr

Expert
Licensed User
Longtime User
i mentioned early on that we had seen a similar problem before. i don't remember much about it except it had something to do with exactly what php returns on an INSERT or a DELETE. a successful operation of these 2 types may not return what you're (reasonably) expecting. see if you can find out what a successful INSERT returns with php. (in other words, you may get success from http but 0 data (or maybe even null). i don't remember.
 
Upvote 0

WebQuest

Active Member
Licensed User
I changed the variable in the processGlobal Public hc As OkHttpClient from private to public in httpUtils2Service and it seems to work as before.
it probably does not receive any data for some localhost problem.
 
Upvote 0

WebQuest

Active Member
Licensed User
Things from another world, the code now doesn't seem to work when I try to find all the rows in the table. Returns a null value.

Response from server : []

Script PHP:
<?php
$databasehost = "localhost";
$databasename = "xxxxxx";
$databaseusername ="xxxxxxx";
$databasepassword = "xxxxxxxx";

$con = mysqli_connect($databasehost,$databaseusername,$databasepassword, $databasename) or die(mysqli_error($con));
mysqli_set_charset ($con , "utf8");
$query = file_get_contents("php://input");
$sth = mysqli_query($con, $query);

if (mysqli_errno($con)) {
   header("HTTP/1.1 500 Internal Server Error");
   echo $query.'\n';
   echo mysqli_error($con);
}
else
{

   $sth=mysqli_query("SELECT Post FROM Comande");

   $rows = array();
   while($r = mysqli_fetch_assoc($sth))
   {
     $rows[] = $r;
   }
   $res = json_encode($rows,true);
    echo $res;
    mysqli_free_result($sth);
}
mysqli_close($con);
?>
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Upvote 0

OliverA

Expert
Licensed User
Longtime User
$sth=mysqli_query("SELECT Post FROM Comande");
Should this not be
B4X:
$sth=mysqli_query($con, "SELECT Post FROM Comande");
?
Otherwise, $sth will never have any records to begin with, explaining the empty result returned.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…