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,450
Last edited:

wmardian

Member
Licensed User
Longtime User
Dear Erel,
In your example, the JSONparser will return a list with maps which contain ID, Country Name.
My question is: How should we do if we want to retrieve 3 fields from database, i.e ID, COUNTRY NAME, CITY NAME ?

Your help will be very appreciated
Thanks and regards

W mardian
 

wmardian

Member
Licensed User
Longtime User
Dear Erel,
Many thanks.. but as i know map can only contain key and value ( 2 fields), so how i should retrieve the third field?

Rgds
 

JUAN CARLOSORDOÑEZ

Member
Licensed User
Longtime User
I need to develop an app for service addresses that takes a remote mysql database and allow me to select and place an order. The request to fill a local temporary table but the order is recorded in the remote database. Thanks for your advice.
 

KMatle

Expert
Licensed User
Longtime User
It depends on the solution and the possibilities to handle the server side (are you able to use php there? Then it is very easy when you like to do it on your own). Security is very good (no passwords inside the app). There are millions of examples in the www. Also see my tutorials.
 

JUAN CARLOSORDOÑEZ

Member
Licensed User
Longtime User
Hello I'm trying mysql.b4a but with my own base. I installed wampserver on my computer. but when you run the application get a message "Error org.apache.http.conn.ConnectTimeoutException: Connect to /192.168.1.103: timeout" I understand that bypass the wait time. I do not have access to make changes in the router about port 80, it's wifi public zone. What i must to active en wampserver icon? Excuse me if you find mistakes in my english. I speak spanish. English...so so..Thanks!!!
 

JUAN CARLOSORDOÑEZ

Member
Licensed User
Longtime User
I have the following code:

req.InitializePost2("mysql16.000webhost.com/DIALER.php", Query.GetBytes("UTF8")) but I get this error:

Error: java.lang.IllegalStateException: Target host must not be null, in September or parameters. scheme = null, host = null, path = mysql16.000webhost.com / DIALER.php, StatusCode: -1


The php script this way:

<? php
$ MYSQL_HOST = "mysql16.000webhost.com";
$ mysql_database = "axxxxxxx_DIALER";
$ mysql_user = "axxxxxxx_DIALER";
$ MYSQL_PASSWORD = "xxxxxxx";
$ con = mysql_connect ($ DatabaseHost, $ DatabaseUserName, $ databasepassword) or die (mysql_error ());
mysql_set_charset ("utf8");
mysql_select_db ($ databasename) or die (mysql_error ());
$ query = file_get_contents ("php: // input");
$ sth = mysql_query ($ query);
if (mysql_errno ()) {
header ("HTTP / 1.1 500 Internal Server Error");
echo $ query '\ n'.;
miss mysql_error ();
}
else
{
$ rows = array ();
while ($ r = mysql_fetch_assoc ($ sth)) {
$ rows [] = $ r;
}
print json_encode ($ rows);
}
?>

please help. Thank you !!
 

JUAN CARLOSORDOÑEZ

Member
Licensed User
Longtime User
It's great technical support. Thank you very much for your cooperation.
When running the application the server responds:
Error: org.apache.http.conn.ConnectTimeoutException: Connect to /10.1.1.116:80 timed out, StatusCode: -1
 

JUAN CARLOSORDOÑEZ

Member
Licensed User
Longtime User
Thanks Erel.

Now I could connect to the server but it responds:

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock'

How can i solve this?

Thanks!!
 

JUAN CARLOSORDOÑEZ

Member
Licensed User
Longtime User
Hello: Download mysql.zip example and it works perfectly. I changed redirecting to another server where I put a base with the same structure but different field name. Obviously I changed the code with the new names but I get an error code.

Response from server: Can not connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

What can be the problem? Thank you !!!
 
Status
Not open for further replies.
Top