Download the free trial version
Basic4android Video
Features
Tutorials and manuals
Showcase
Screenshots

Go Back   Android Development Forum - Basic4android > Basic4android > Basic4android Getting started & Tutorials
Documentation Wiki Register Members List Windows Mobile Search Today's Posts Mark Forums Read

Basic4android Getting started & Tutorials Android development starts here. Please do not post questions in this sub-forum.

Connect Android to MySQL Database Tutorial

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 03-21-2011, 04:07 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,824
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default Connect Android to MySQL Database Tutorial

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:


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 Code:
<?

$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());
$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.



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.
Attached Files
File Type: zip MySQL.zip (10.1 KB, 481 views)
Reply With Quote
  #2 (permalink)  
Old 03-21-2011, 06:16 PM
alwaysbusy's Avatar
Junior Member
 
Join Date: Oct 2007
Location: Belgium
Posts: 94
Default

Thanks Erel! Great tutorial
Reply With Quote
  #3 (permalink)  
Old 03-22-2011, 09:27 PM
JMB JMB is offline
Junior Member
 
Join Date: Jan 2011
Location: Shetland Islands, UK
Posts: 69
Default Thanks

Thanks Erel - have been working on something very similar and was thinking of posting it for the benefit of other users, but this covers things in really useful detail.
Reply With Quote
  #4 (permalink)  
Old 03-31-2011, 07:59 PM
ruy ruy is offline
Newbie
 
Join Date: Feb 2011
Posts: 8
Exclamation MySql example

Hi, I am new to Basic4Droid and while experimenting with this example I find that it works fine as is. But if I try to replicate the php web service in my server and using my database, it simply refuses to work. When it reads the first table (Names & Id's) it sends the following message:

"An error has occurredin sub:main_hc_responsesuccess (B4A line:63)
countries = parser.NextArray 'returns a list with maps
java.lang.RuntimeException: JSON Array expected.
continue?"


It is an exact replica of the files in the tutorial except for quotes missing in the php listing for the MySql server credentials (which I changed for the ones in my server/database) and the address of the php file.

The log file shows identical structures for the one that runs with the original http://www.basic4ppc.com/android/countries.php and the one that runs at mt server, though, it refuses to continue.

What am I doing wrong?

Ruy
Reply With Quote
  #5 (permalink)  
Old 04-01-2011, 10:55 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,824
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

Looking at the logcat of your server response lead me to the solution:


Instead of a square bracket there is a strange character.
Checking the actual bytes received showed that your server is sending the text as UTF8 with BOM marking. The BOM (byte order marking) are three bytes at the beginning of the stream. I recommend you to configure your server to not send it as it is not expected and may cause all kinds of strange problems.

You can workaround it by removing the first character:
Code:
Sub hc_ResponseSuccess (Response As HttpResponse, TaskId As Int)
    
Dim res As String
    res = Response.GetString(
"UTF8")
    res = res.SubString(
1'removes first character
Reply With Quote
  #6 (permalink)  
Old 04-01-2011, 03:15 PM
ruy ruy is offline
Newbie
 
Join Date: Feb 2011
Posts: 8
Default

Excellent, this solved the problem!

Thanks for the prompt response and congratulations for the great service.

Ruy
Reply With Quote
  #7 (permalink)  
Old 04-01-2011, 08:07 PM
ruy ruy is offline
Newbie
 
Join Date: Feb 2011
Posts: 8
Exclamation

My database uses Spanish words with accents and Ñ, the fields that contain any of these characters return "NULL" how may I solve this. I guess it is using a different encoding than UTF8 but I cant find the alternatives for this encoding value.

Reply With Quote
  #8 (permalink)  
Old 04-02-2011, 05:48 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,824
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

First make sure that the data was inserted correctly. Open the database with a tool like PhpMyAdmin and check that the data exists.

You can use the Convert MySQL function to convert strings to UTF8:
MySQL :: MySQL 5.0 Reference Manual :: 11.10 Cast Functions and Operators
Code:
SELECT CONVERT(Column1 USING utf8) FROM ...
Reply With Quote
  #9 (permalink)  
Old 04-02-2011, 03:42 PM
ruy ruy is offline
Newbie
 
Join Date: Feb 2011
Posts: 8
Default

I had already tried that already to no avail :-(
Reply With Quote
  #10 (permalink)  
Old 04-02-2011, 03:45 PM
ruy ruy is offline
Newbie
 
Join Date: Feb 2011
Posts: 8
Default

I tried both options: CONVERT(expr,utf8), CONVERT(expr USING utf8)
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Android JSON Tutorial klaus German Tutorials 0 02-11-2011 10:31 PM
Android Serial Tutorial klaus German Tutorials 0 01-26-2011 09:05 PM
connect to mysql server from device encolo Questions (Windows Mobile) 5 08-30-2010 04:50 PM
How To Connect Basic 4ppc With Mysql ? jothis Questions (Windows Mobile) 2 05-18-2010 09:50 PM
connect or sync database in PPC from Desktop kalmenchia Questions (Windows Mobile) 1 01-09-2010 08:41 AM


All times are GMT. The time now is 07:50 PM.


Powered by vBulletin® Version 3.6.12
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0