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

danvica

Member
Licensed User
Longtime User
Yes. It works :sign0104:.

Just for reference. I modified the PHP script in this way:

B4X:
if (!isset($_GET["insert"]))
{
    $rows = array();
    while($r = mysql_fetch_assoc($sth))
    {
        $rows[] = $r;
    }
    print json_encode($rows);
}

And then, just for the INSERT queries, I call the script adding ?insert variable.
 

danvica

Member
Licensed User
Longtime User
Just one more small thing.

When the views in the table are cleared and recreated you don't see any refresh flickering. This is wounderfull but... why ? It seems the refresh of the table is stopped until the last row (i.e. the very last table.addview) is executed...

And moreover you don't loose the current table position. I.e. if you are viewing the middle of the table, after a refresh, you are still in the same position...I understand in this case the table is just a container of label views but this means I can change the focus position of an empty table to whatever position I want ?
 

pluton

Active Member
Licensed User
Longtime User
I have one question.
In my project I need just this example but i want to hide second line like I normal do in ListView and center text of the first one. Why my code is not working when i make:

B4X:
title = ListView1.TwoLinesAndBitmap.Label
title.TextSize = 20
title.TextColor = Colors.Yellow
title.Gravity = Gravity.CENTER
ListView1.TwoLinesAndBitmap.SecondLabel.Visible = False
:BangHead:
 

pluton

Active Member
Licensed User
Longtime User
Yes. Thank You Erel.

Without you I will die.

I'm so stupid. Million times I call "TwoLinesAndBitmap" and didn't notice that it needs TwoLines.

Thanks
 

KrLxroller

New Member
Why have I to pay to download attached files? I'm doing a research project for my University, this post and the files attached seem to be the only way for me to understand how to connect my application to a MySQL DB, and I realize that I have to pay to "get full access to the site". I do not understand it. Android is a free OS. Developers should help each other in order to learn and to create better applications... I understand that there are people who want to earn some money creating forums, webpages etc. But... Have I to pay to learn? I do not think so... I think that adverts are a great way to earn some money. It is fair if you want to get money selling the "Basic4android" tools, but it is unfair if I must pay to download an attached file.

Sorry for the off-topic but I'm a bit angry.
 
Last edited:

hdtvirl

Active Member
Licensed User
Longtime User
Try and buy a book for the cost of B4A

My friend, college has just started for 2011-2012 and some of the prescribed reading on Android development cost more than the student discount Price of V4A and you will get more help and knowledge for your mone y from this site. Sure eclispe is free but it will take you alot longer to master.

I don't know what your research project is but I would prefer to spend more time on my project than debuging my Java code. I have not received my project yet but I know one thing B4A will be the code behind it and when I get my final results I will be more than happy to renew my license with Erel by way of thanks.

So take the plunge and spend some of your beer money and buy the student copy you won't regret it!


Regards

BOB
 

oleman108

Member
Licensed User
Longtime User
The example code is not working for me (yet)

I'm note lucky with getting anything back from MySQL Server. No error, no data. I am not really familiar with LAMP and so I do not know yet how to debug this.
I have a VPS server with MySQL and I have put up some test code which gives me a result as expected.

Any idea how I can make this tutorial run, what to do next? :sign0163:

My working Webservice:
http://www.dharma.ch/promos/

With this php code:
B4X:
<?php
 
class RedeemAPI {
    private $db;
 
    // Constructor - open DB connection
    function __construct() {
        $this->db = new mysqli('localhost', 'testuser', 'testarossa', 'rcdata');
        $this->db->autocommit(FALSE);
    }
 
    // Destructor - close DB connection
    function __destruct() {
        $this->db->close();
    }
 
    // Main method to redeem a code
    function redeem() {
        // Print all codes in database
        $stmt = $this->db->prepare('SELECT ID, Name, Population FROM countries');
        $stmt->execute();
        $stmt->bind_result($ID, $Name, $Population);
        while ($stmt->fetch()) {
            echo "$Name has $Population units.<br>";
        }
        $stmt->close();
    }
}
 
// This is the first thing that gets called when this page is loaded
// Creates a new instance of the RedeemAPI class and calls the redeem method
$api = new RedeemAPI;
$api->redeem();
?>
 

oleman108

Member
Licensed User
Longtime User
Error-log

Did you check the logs in the right pane?
Okay, now there is something. There is an error (Error: Internal Server Error, StatusCode: 500) which I do not understand:
B4X:
LogCat connected to: B4A-Bridge: samsung GT-I9100-358848043960947
--------- beginning of /dev/log/system
--------- beginning of /dev/log/main
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Service (service1) Create **
** Service (service1) Start **
** Service (service1) Start **
Connected to B4A-Bridge
Installing file.
** Activity (main) Pause, UserClosed = false **
PackageAdded: package:anywheresoftware.b4a.agraham.dialogsdemo
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = true **
** Activity (main) Resume **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Service (service1) Create **
** Service (service1) Start **
** Service (service1) Start **
Connected to B4A-Bridge
Installing file.
** Activity (main) Pause, UserClosed = false **
PackageAdded: package:anywheresoftware.b4a.agraham.dialogsdemo
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Resume **
** Service (service1) Destroy **
** Activity (main) Pause, UserClosed = true **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Service (service1) Create **
** Service (service1) Start **
** Service (service1) Start **
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = true **
Connected to B4A-Bridge
Installing file.
PackageAdded: package:anywheresoftware.b4a.samples.mysql
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
Error: Internal Server Error, StatusCode: 500
** Activity (main) Create, isFirst = false **
** Activity (main) Resume **
** Service (service1) Start **
** Service (service1) Destroy **
** Service (service1) Create **
** Service (service1) Start **
Connected to B4A-Bridge
Installing file.
** Activity (main) Pause, UserClosed = false **
PackageAdded: package:anywheresoftware.b4a.samples.mysql
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
Error: Internal Server Error, StatusCode: 500
What could that be?
 

oleman108

Member
Licensed User
Longtime User
Yes, I copied your code and changed the values for databasename, -username and -password. The login and query works with the php script I previously posted here.
The only errormessage I'm getting says: "Error: Internal Server Error, StatusCode: 500". Which leads me to the question: WHICH server is meant here?

FYI: I am working on MacBook Pro from a Windows7 VMWare Client and I have a Samsung Galaxy2S connected via B4A Bridge. When I comile and run the MySQL.b4a project, then on the Galaxy I am getting a black screen with 2 labels on it: Country: and Population: - that's all. Plus the "Internal Server Error, StatusCode: 500" message. Is this an error coming from MySQL?
 

pluton

Active Member
Licensed User
Longtime User
Yes, I copied your code and changed the values for databasename, -username and -password. ....
....Is this an error coming from MySQL?


That is error from your server.
Did you crate table on your server with this fields ????

You must create table with 3 fields in it:

Name (put as varchar)
ID (put as varchar)
Population (put as Int)
 

arturataide

Member
Licensed User
Longtime User
error

Hi!
I'm getting the fallowing error:

B4X:
Response from server: <br /> <b> Parse error</b>: syntax error, unexpected T_STRING in <b> ** my server**/connect.php</b>on line <b>10</b> <br/>

my php code in line 10 is
PHP:
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = file_get_contents("php://input"); 
$sth = mysql_query($query);

i need some help please
thanks in advance
artur ataíde
 

pluton

Active Member
Licensed User
Longtime User
What is in line 10 ?????
Exactly what code ??

Post here your PHP code. If you copy the code from first post it is missing " in it.

It has mistake so Erel forgot to corrected it.
It is here:
PHP:
<?

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

It must be: $databasepassword = "xxxx";
 
Last edited:
Status
Not open for further replies.
Top