Android Tutorial Connect Android to MySQL Database Tutorial

Status
Not open for further replies.
A new more powerful framework is now available: jRDC2.

This tutorial explains the basic concepts required for creating a connection between Android device and a remote server. In this case it is a MySQL database.
A tutorial for connecting to SQL Server is available here.

Android cannot connect directly to the database server (search for JdbcSQL). Therefore we need to create a simple web service that will pass the requests to the database and will return the response.

For this example I've created a new database that lists the countries population. The data was derived from a UN database.

The database includes a single table named "countries" with three columns:
mysql_1.png

PHP Script

The web service is made of a single PHP script running on the same server.
You have several options for the web service implementation. You can create several prepared statements which will be filled with parameters passed in the request.
Or you can take the complete query from the request and pass it to the database server.
There are high security risks with issuing queries received from an unknown user. If your service is public then you will probably want to choose the first option.
You should also make sure to correctly escape the parameters. See this php method: PHP: mysql_real_escape_string - Manual

In our example I've chosen the second option which takes the query and passes it to the database directly.
I've restricted the database user to SELECT queries (in MySQL configuration).

The PHP code:
PHP:
<?php

$databasehost = "localhost";
$databasename = "xxxx";
$databaseusername ="xxxx";
$databasepassword = "xxxx";

$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);
    echo $res;
    mysqli_free_result($sth);
}
mysqli_close($con);
?>
The script takes the query from the POST data and submits it to the database.
The result is then written in JSON format.

B4A code

Our application displays a list of countries. When the user presses on a country, its population is retrieved from the database and displayed.

upload_2016-8-3_13-4-25.png



The code sends the query and then when the result arrives the JSON is parsed and displayed.
Note that in this case the JSON object is made of an array of one or more maps.

Edit: Code updated to use OkHttpUtils2.
 

Attachments

  • MySQL.zip
    8 KB · Views: 17,491
Last edited:

artefact

Member
Licensed User
Longtime User
java.lang.RuntimeException: JSON Array expected.


at anywheresoftware.b4a.objects.collections.JSONParser.NextArray(JSONParser.java:62)
at anywheresoftware.b4a.samples.mysql.main._jobdone(main.java:398)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:174)
at anywheresoftware.b4a.keywords.Common$5.run(Common.java:952)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)


java.lang.RuntimeException: JSON Array expected.
 

artefact

Member
Licensed User
Longtime User
I have precised you that this error appears when I connect via wifi network but I can not logging me on this network...
On error, Log("Response from server: " & res) manages perfectly with ToastMessageShow.
But this error does not seem to be taken into account...
 

artefact

Member
Licensed User
Longtime User
I use exactly the same example that you propose in the tutorial.
Here is the complete code :

B4X:
** Activity (main) Create, isFirst = true **


** Activity (main) Resume **


** Service (httputils2service) Create **


** Service (httputils2service) Start **


Response from server: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<meta name="viewport" content="width=400, user-scalable = no" />

<title></title>

<link rel="stylesheet" type="text/css" href="/css/small.css" media="screen" />

</head>

<body>

<div id="header">

  <div id="header_c">

    <div id="top">

      <div id="top-menu"><img src="/im/logo2.png" width="232" height="112" alt="Free" /></div>

    </div>

  </div>

  <div class="clearer"></div>

</div>

<div id="bod">

  <div id="bod_c">

    <div id="block">

      <h1>CONNEXION AU SERVICE <span class="red">FreeWiFi</span></h1>

      <br />

      <div id="block_2">

        <p >Pour vous connecter au service FreeWiFi, <br />

          utilisez les identifiants que vous avez configurés lors de votre premier accès au service<br />

        <form id="form1" name="form1" method="post" action="/Auth">

          <label for="login" class="label" > IDENTIFIANT</label>



          <input name="login" id="login"  class="input_r" value=""/>

          <br />

          <br />

          <br />

          <label for="password" class="label" > MOT DE PASSE</label>

          <input type="password" name="password" id="password" class="input_r" value=""/>

          <br />

          <br />

          <br />

<!--          <a href="#" class="label" style="padding-top:0px;"><img src="/im/help.png" alt="ASSISTANCE" width="37" height="40" border="0"  /></a>

-->

<!--      <input name="priv" id="priv" type="hidden"  value="" /> -->

          <input name="submit" type="submit" value="Valider" class="input_b" />

        </form>

       

    

         <div class="clearer"></div>

      </div>



      <a href="/?priv=$PRIV_SUB"><img src="/im/abo.jpg" alt="Vous n'êtes pas abonné FREE? Cliquez ici et dans une minute, vous pourrez accéder à internet" width="399" height="70" border="0" /></a></div>

  </div>

</div>

</body>

</html>

java.lang.RuntimeException: JSON Array expected.


    at anywheresoftware.b4a.objects.collections.JSONParser.NextArray(JSONParser.java:62)
    at anywheresoftware.b4a.samples.mysql.main._jobdone(main.java:398)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:174)
    at anywheresoftware.b4a.keywords.Common$5.run(Common.java:952)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)


java.lang.RuntimeException: JSON Array expected.
 

artefact

Member
Licensed User
Longtime User
The server is configured correctly but I'm not saved me on that server....
Once connected (login+password), all works perfectly!
The HTML code is the home page for connecting to the service.
 
Last edited:

catyinwong

Active Member
Licensed User
Longtime User
<code>
<?
$QueryString = file_get_contents("php://input");
list($databasehost, $databasename, $databaseusername, $query) = explode('/', $QueryString);

if ($databasehost <> "") {
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
$query = file_get_contents("php://input");
$sth = mysql_query($query);

if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query.'\n';
echo mysql_error();
}
else
{
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
}
}

?>
<code>

Trying to build a php that can adapt to various sql server but the above doesn't work.. anyone helps?? :(
 

BarryW

Active Member
Licensed User
Longtime User
A new more powerful framework is now available: Remote Database Connector.

This tutorial explains the basic concepts required for creating a connection between Android device and a remote server. In this case it is a MySQL database.
A tutorial for connecting to SQL Server is available here.

Android cannot connect directly to the database server. Therefore we need to create a simple web service that will pass the requests to the database and will return the response.

For this example I've created a new database that lists the countries population. The data was derived from a UN database.

The database includes a single table named "countries" with three columns:
mysql_1.png

PHP Script

The web service is made of a single PHP script running on the same server.
You have several options for the web service implementation. You can create several prepared statements which will be filled with parameters passed in the request.
Or you can take the complete query from the request and pass it to the database server.
There are high security risks with issuing queries received from an unknown user. If your service is public then you will probably want to choose the first option.
You should also make sure to correctly escape the parameters. See this php method: PHP: mysql_real_escape_string - Manual

In our example I've chosen the second option which takes the query and passes it to the database directly.
I've restricted the database user to SELECT queries (in MySQL configuration).

The PHP code:
PHP:
<?

$databasehost = "localhost";
$databasename = "xxxx";
$databaseusername ="xxxx";
$databasepassword = "xxxx";

$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
$query = file_get_contents("php://input");
$sth = mysql_query($query);

if (mysql_errno()) {
    header("HTTP/1.1 500 Internal Server Error");
    echo $query.'\n';
    echo mysql_error();
}
else
{
    $rows = array();
    while($r = mysql_fetch_assoc($sth)) {
        $rows[] = $r;
    }
    print json_encode($rows);
}
?>
The script takes the query from the POST data and submits it to the database.
The result is then written in JSON format.

Basic4android code

Our application displays a list of countries. When the user presses on a country, its population is retrieved from the database and displayed.

SS-2013-01-29_16.42.32.png


The code sends the query and then when the result arrives the JSON is parsed and displayed.
Note that in this case the JSON object is made of an array of one or more maps.

Edit: Code updated to use HttpUtils2 instead of HttpClient.

Hi. Can we send multiple query using this tutorial?

Like:
ExecuteRemoteQuery("INSERT INTO table1 VALUES('test1','test2'); INSERT INTO table2 VALUES('test3','test4')", "insert")

Tnx...
 

Treyvanoft

Member
Licensed User
Longtime User
It is difficult to read the screenshot. Please post the text directly next time.

Try to remove HttpJob and HttpUtils2Service modules and add a reference to HttpUtils2 library instead.
thank you. it's error because set android path. i change to android-22 it's can work.
 

Vern

Member
Licensed User
Longtime User
I'm new to B4A and just downloaded this code. The IDE shows:

Unknown type: httpresponse
Are you missing a library reference?

Unknown type: httpclient
Are you missing a library reference?

If I try to run the code, I get:

B4A version: 5.00
Parsing code. Error
Error parsing program.
Error description: Unknown type: jsonparser
Are you missing a library reference?
Occurred on line: 54
Dim parser As JSONParser

Any clue why these references don't work or how to fix them?
 

RandomCoder

Well-Known Member
Licensed User
Longtime User
The example you are trying to test uses libraries which you have not yet downloaded. As a licenced user you can search and download the required libraries directly from this Forum. Just search for each library, then download the zip file. Finally you need to extract the contents and save them to your libraries folder which is the path you set when you first installed B4A. The final step is to select the new libraries from the libraries tab on the right hand pane of the IDE. All should then work correctly without any errors.

Ps. There are many libraries created for B4A and they greatly extend the functionality and features available to you. Some require a small fee or donation but the majority are completely free to use however you choose.
 
Status
Not open for further replies.
Top