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 B4P 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, 05:07 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 13,385
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.



This is the code (project is attached):
Code:
Sub Process_Globals
    
Dim hc As HttpClient
    
Dim COUNTRIES_LIST, COUNTRY_POPULATION As Int
    COUNTRIES_LIST = 
1
    COUNTRY_POPULATION = 
2
End Sub

Sub Globals
    
Type TwoLines (First As String, Second As String)
    
Dim lblPopulation As Label
    
Dim ListView1 As ListView
    
Dim lblCountry As Label
End Sub

Sub Activity_Create(FirstTime As Boolean)
    
If FirstTime Then
        hc.Initialize(
"hc")
    
End If
    Activity.LoadLayout(
"1")
    FetchCountriesList
End Sub
Sub FetchCountriesList
    
ProgressDialogShow("Fetching list of countries")
    
'Gets all the available countries
    ExecuteRemoteQuery("SELECT name, id FROM countries ORDER BY id", COUNTRIES_LIST)
End Sub
Sub ListView1_ItemClick (Position As Int, Value As Object)
    
If IsBackgroundTaskRunning(hc, COUNTRY_POPULATION) Then
        
ToastMessageShow("Wait for previous call to finish."False)
        
Return
    
End If
    
Dim tl As TwoLines
    tl = Value
    lblCountry.Text = tl.Second
    lblPopulation.Text = 
"Calling server..."
    ExecuteRemoteQuery(
"SELECT population FROM countries WHERE id='" & tl.First & "'", COUNTRY_POPULATION)
End Sub
Sub ExecuteRemoteQuery(Query As String, TaskId As Int)
    
Dim req As HttpRequest
    req.InitializePost2(
"http://www.basic4ppc.com/android/countries.php", query.GetBytes("UTF8"))
    hc.Execute(req, TaskId)
End Sub
Sub hc_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
    
Log("Error: " & Reason & ", StatusCode: " & StatusCode)
    
If Response <> Null Then
        
Log(Response.GetString("UTF8"))
        Response.Release
    
End If
    
ProgressDialogHide
End Sub
Sub hc_ResponseSuccess (Response As HttpResponse, TaskId As Int)
    
Dim res As String
    res = Response.GetString(
"UTF8")
    
Log("Response from server: " & res)
    
Dim parser As JSONParser
    parser.Initialize(res)
    
Select TaskId
        
Case COUNTRIES_LIST
            
'add the countries to the ListView
            Dim countries As List
            countries = parser.NextArray 
'returns a list with maps
            For i = 0 To countries.Size - 1
                
Dim m As Map
                m = countries.Get(i)
                
'We are using a custom type named TwoLines (declared in Sub Globals).
                'It allows us to later get the two values when the user presses on an item.
                Dim tl As TwoLines
                tl.First = m.Get(
"id")
                tl.Second = m.Get(
"name")
                ListView1.AddTwoLines2(tl.First, tl.Second, tl)
            
Next
            
ProgressDialogHide
        
Case COUNTRY_POPULATION
            
Dim l As List
            l = parser.NextArray
            
If l.Size = 0 Then
                lblPopulation.Text = 
"N/A"
            
Else
                
Dim m As Map
                m = l.Get(
0)
                lblPopulation.Text = 
NumberFormat2(m.Get("population"),000True) & " (K)"
            
End If
    
End Select
    response.Release
End Sub
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.
Attached Files
File Type: zip MySQL.zip (6.5 KB, 1429 views)
__________________
Basic4android documentation
Reply With Quote
  #2 (permalink)  
Old 03-21-2011, 07:16 PM
alwaysbusy's Avatar
Knows the basics
 
Join Date: Oct 2007
Location: Belgium
Posts: 77
Default

Thanks Erel! Great tutorial
Reply With Quote
  #3 (permalink)  
Old 03-22-2011, 10:27 PM
JMB JMB is offline
Knows the basics
 
Join Date: Jan 2011
Location: Shetland Islands, UK
Posts: 67
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, 08: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, 11:55 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 13,385
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
__________________
Basic4android documentation
Reply With Quote
  #6 (permalink)  
Old 04-01-2011, 04: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, 09: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, 06:48 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 13,385
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 ...
__________________
Basic4android documentation
Reply With Quote
  #9 (permalink)  
Old 04-02-2011, 04: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, 04: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 11:31 PM
Android Serial Tutorial klaus German Tutorials 0 01-26-2011 10:05 PM
connect to mysql server from device encolo Questions (Windows Mobile) 5 08-30-2010 05:50 PM
How To Connect Basic 4ppc With Mysql ? jothis Questions (Windows Mobile) 2 05-18-2010 10:50 PM
connect or sync database in PPC from Desktop kalmenchia Questions (Windows Mobile) 1 01-09-2010 09:41 AM


All times are GMT. The time now is 02:56 AM.


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