Send data from android to server via JSON

26,752

Solution 1

To send data to server you could do this:

private void sendData(ArrayList<NameValuePair> data)
{
     // 1) Connect via HTTP. 2) Encode data. 3) Send data.
    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new      
        HttpPost("http://www.blah.com/AddAccelerationData.php");
        httppost.setEntity(new UrlEncodedFormEntity(data));
        HttpResponse response = httpclient.execute(httppost);
        Log.i("postData", response.getStatusLine().toString());
            //Could do something better with response.
    }
    catch(Exception e)
    {
        Log.e("log_tag", "Error:  "+e.toString());
    }  
}

then to send lets say:

private void sendAccelerationData(String userIDArg, String dateArg, String timeArg,
        String timeStamp, String accelX, String accelY, String accelZ)
{
    fileName = "AddAccelerationData.php";

    //Add data to be send.
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
    nameValuePairs.add(new BasicNameValuePair("userID", userIDArg));
    nameValuePairs.add(new BasicNameValuePair("date",dateArg));
    nameValuePairs.add(new BasicNameValuePair("time",timeArg));
    nameValuePairs.add(new BasicNameValuePair("timeStamp",timeStamp));

    nameValuePairs.add(new BasicNameValuePair("accelX",accelX));
    nameValuePairs.add(new BasicNameValuePair("accelY",accelY));
    nameValuePairs.add(new BasicNameValuePair("accelZ",accelZ));

    this.sendData(nameValuePairs);
}

so then the AddAccelerationData.php file on server is:

<?php
/*
 * What this file does is it:
 * 1) Creates connection to database.
 * 2) Retrieve the data being send.
 * 3) Add the retrieved data to database 'Data'.
 * 4) Close database connection.
 */
require_once '../Connection.php'; //connect to a database/disconnect handler.
require_once '../SendAPI.php'; //deals with sending querys.

$server = new Connection();
$send = new Send();

//Connect to database.
$server->connectDB();

//Retrieve the data.
$userID = $_POST['userID'];
$date = $_POST['date'];
$time = $_POST['time'];

$accelX = $_POST['accelX'];
$accelY = $_POST['accelY'];
$accelZ = $_POST['accelZ'];

//Add data to database 'Data'. //Personal method to query and add to database.
$send->sendAccelerationData($userID, $date, $time, $timeStamp, $accelX, $accelY, $accelZ);


//Disconnect from database.
$server->disconnectDB();
?>

This is an example I used recently. Just to note in the php file. I import Connection.php this just deals with the connection to the database. So just replace that with your code for connecting to MYSQL db. Also I imported SendAPI.php (which you can just ignore)This was just my class for sending data. Basically it contained some of the querys I wanted to use. Such as sendAccelerationData(). Basically class was similar to that of stored procedures.

Solution 2

Since an Android application cannot connect directly to a MySQL server you need to write a kind of a "bridge".

UPDATE: @see Femi's comment

Well, technically speaking, It could: http://developer.android.com/reference/javax/sql/package-summary.html

But for security reasons a bridge is a mandatory choice IMHO.

One one the most popular approach is to use the http protocol for sending and reading data.

Your city.php will contain the logic for connect and querying the database:

<?php
$db = mysql_connect(....);
//query...
echo json_encode($data);
?>

The Android app will connect trough your server and will parse the json output.

So yes, you need to write the server-side part and client side part (Android)

A really useful video: http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html

Code sample with PHP as bridge and Android via http protocol:

http://www.helloandroid.com/tutorials/connecting-mysql-database

Solution 3

You do need to update and retrieve through JSON ? If this is the case, you'll probably have to code some Web Service and such, (it won't necessarily be in PHP, could be Java, C#, whatever)

Look at this thread, it seem there is no way you can access MySql server directly from android, so indeed, you may need some Web development implement the JSON/XML middle layer to connect with android.

Thread @ StackOverFlow Android + MySQL using com.mysql.jdbc.Driver

Solution 4

You can do it by using JDBC. I did an application that talked with MYSQL using JDBC standard API. Please bear in mind that not all connectors works, the only one I know is mysql-connector-java-3.0.17-ga-bin.jar.

You'll need to implement a pool of connections to speed up query response times cause JDBC put a little overhead to Android when building a connection to server, it takes 2 to 3 seconds to start but once connected works very fast.

Share:
26,752
Yoo
Author by

Yoo

Updated on September 15, 2020

Comments

  • Yoo
    Yoo over 3 years
    1. I have MySQL database server
    2. I need to update and retrieve data to/from MySQL server via JSON

    So, I want to know how to do that, and I pretty confuse with this example statement:

    HttpPost httppost = new HttpPost("http://10.0.2.2/city.php");
    

    This means I need to code my application that connect with PHP server before write php to connect to DB right ?

  • Femi
    Femi almost 13 years
    Actually, there's nothing that says an Android application can't talk directly to MySQL: see developer.android.com/reference/java/sql/package-summary.htm‌​l and developer.android.com/reference/javax/sql/package-summary.ht‌​ml. JDBC is natively supported in Android: you would need to add the MySQL JDBC drivers, but you can definitely do it. Now, the bridge IS useful for security type details, but you can definitely do JDBC in Android.
  • Yoo
    Yoo almost 13 years
    @Francesco: So, I understand the point that I must write a code to connect to PHP server then it will connect to DB later. Otherwise, I cannot immagine how can I fetch the data from MySQL server to my application. Could you please give me some details. Thanks
  • Francesco Laurita
    Francesco Laurita almost 13 years
    @Femi, you are totally right even if any client type software that connects directly to a database is badly written IMHO. Using the ssl connection become a must have otherwise put a sniffer and have fun with the db!
  • Francesco Laurita
    Francesco Laurita almost 13 years
    @Daisy, Just added some useful links on my answer
  • Yoo
    Yoo almost 13 years
    Last question before implement, shall I install any library(.jar) in my android application package ?
  • Francesco Laurita
    Francesco Laurita almost 13 years
    @Daisy if you want talk directly to MySQL you need the MySQL jdbc driver, otherwise no third party libraries are needed
  • Adam Varhegyi
    Adam Varhegyi almost 12 years
    I get ClientProtocolExcaption can you help me out why i got this?