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

GR88sa

New Member
Licensed User
Longtime User
Insert Query - Not possible

Error: org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused, StatusCode: -1

This is the error apears when i try run this project on local area network, using Wamp and android emulator.

I'm new on Basic4Android

Help me please! :sign0163:
 

sigster

Active Member
Licensed User
Longtime User
Hi

I try this code
I can run it but I don't get country list

this popup maybe 1 sec and diapers then nothing
ProgressDialogShow("Fetching list of countries")

I am using remote server not localhost

Regards
Sigster
 

TomDuncan

Active Member
Licensed User
Longtime User
Instead of localhost put in the pcpip addesss of your server. Works for me.
Tom:sign0104:
 

sigster

Active Member
Licensed User
Longtime User
Know it work I did not change anything ? chance the path into wront path and then back and it work ! ??

but I have problem with characters like ð,æ if name have this characters
then I get NULL in Listview

Thanks
 

sigster

Active Member
Licensed User
Longtime User
Finish to fix this
know I nont get NULL if characters is ð,æ

-->>> mysql_query("SET NAMES 'UTF8'");

$query = file_get_contents("php://input");
$sth = mysql_query($query);

Thanks
Sigater
 

Arbel

New Member
Licensed User
Longtime User
Why can't I read my data!!

Hi All,

I just follow MySQL sample code but pointing our database and no errors, everything looks ok but no data is returned on the response function.
I can execute the php part on my server and the result is exactly as expected
[{"name":"Peter, Sellers", "id":"......
but nothing on the res = Response.GetString("UTF8"). Wired!!!

Any ideas at all???
I'm just desperate!
 

jegadk

Member
Licensed User
Longtime User
Any chance to get the exact same sample, just with an asp script.

Have this code to work in my asp

response.write QueryToJSON(myConn, "SELECT name,id FROM countries ORDER BY id").flush

But

response.write QueryToJSON(myConn, request.querystring).flush

fails, because i can't read anything in the querystring. Debugging shows that Query.GetBytes("UTF8") says "SELECT name,if FROM countries...."


Jesper
 

isk2837

Member
Licensed User
Longtime User
Trying to make an app that connects to a database, but the log keeps containing this error - Error: java.lang.IllegalArgumentException: Host name may not be null, StatusCode: -1

What does this mean exactly? I'm still completely new to this program, so can someone explain to me what it could mean is wrong?
 

guidoarfini

Member
Licensed User
Longtime User
mysql to bitmap

Hello, I had previously built the database (sqlite) and I used cursor1.getblob, now I have moved all from mysql server with php, but how do I transfer the photos because I like Null response from mysql? If I find as I look at mysql BLOB Binary Data


Sub hc_ResponseSuccess (Response As HttpResponse, TaskId As Int)
Msgbox("server Connect!","")

'VARIABILI TABLE SERVIZI
Dim IDArtista,Cognome,Nome,Pseudo,Nazionalita,TipoArtista,DataNascita,FotoArtista As String


Dim res As String
res = Response.GetString("UTF8")
Log("Response from server: " & res)
Dim parser As JSONParser
parser.Initialize(res)
Select TaskId
Case Artiste_list
Dim VerfArtista As List
VerfArtista = parser.NextArray
For I = 0 To VerfArtista.Size -1
Dim M As Map
Dim InputStream1 As InputStream
Dim Buffer() As Byte
Dim Bitmap1 As Bitmap

M = VerfArtista.Get(I)
IDArtista=M.Get("IDArtista")
Cognome=M.Get("Cognome")
Nome=M.Get("Nome")
Pseudo=M.Get("Pseudo")
Nazionalita=M.Get("Nazionalita")
TipoArtista=M.Get("TipoArtista")
DataNascita =M.Get("DataNascita")

Buffer = M.Get("FotoArtista")
InputStream1.InitializeFromBytesArray(Buffer, 0, Buffer.Length)
Bitmap1.Initialize2(InputStream1)
InputStream1.Close




ListaArtiste.AddTwoLinesAndBitmap2(Pseudo,Nazionalita,Bitmap1,IDArtista)

Next
 
Status
Not open for further replies.
Top