Upload JSON Data from Android Phone to MySQL Database on Website / Server Example

Here is an example of uploading Json Data to a MySQL database on a website/Server from a Android phone.  This is great to upload user data from the phone to a website. The bad thing is  that you have to use a different Thread instead of the main UI thread. It fairly simple to multithread even though some examples  makes it pretty complicated. Check out my attempted to explain an example of using the Android Thread class.

Android side uploading the Json data (This Assume you know how to use different threads): 

    static ProgressDialog pd; // For threading
    static  Handler handle = new Handler();  // For threading

    /** Use your own parameters **/
	public static void postData(Trip trip, String units, Boolean location, String message) throws JSONException{  
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://yoursite.com/file_where_the script_below_is_located.php");
        JSONObject json = new JSONObject();

        try {
            /** Add your data into the json **/	
            json.put("date", trip._date);
	    json.put("lat", trip._latitude);
	    json.put("log", trip._longitude);
            json.put("message", message);
            json.put("speed", trip._maxspeed);
            json.put("distance", trip._distance);
            json.put("alt", trip._altitude);
            json.put("unit", units);

            JSONArray postjson=new JSONArray();

            // Post the data:

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            // for JSON:
            if(response != null)
                InputStream is = response.getEntity().getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();

                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                } catch (IOException e) {
                } finally {
                    try {
                    } catch (IOException e) {

            /** Most below is related to multithreading **/
            pd.dismiss(); //Threading
		    handle.post(Success); //Threading 
        }catch (ClientProtocolException e) {
		    handle.post(Success); // Threading
            // TODO Auto-generated catch block
        } catch (IOException e) {
		    handle.post(Success); //Threading 
            // TODO Auto-generated catch block

    /**Used for Multithreading **/
	final static Runnable Success = new Runnable() {
		   public void run() {


Here is the method calling this method. Ignore this if you already know how to multithread but if not then its a start.

    public void upload(final int index, final Boolean location, final String text){
        pd = ProgressDialog.show(this, "Uploading" , "");
	      Thread t = new Thread() {
	          public void run() {
			        try {	
			            Service.postData(dh.getTrip(index), "us", location, text);
			        } catch (JSONException e) {
			            // TODO Auto-generated catch block


Server Side (This assumes you know basic PHP/MySQL):

    $json = $_SERVER['HTTP_JSON'];

    $data = json_decode($json);

    $date = $data->date;
    $lat = $data->lat;
    $log = $data->log;
    $speed = $data->speed;
    $distance = $data->distance;
    $alt = $data->alt;
    $unit = $data->unit;
    $message = $data->message;

  $conn = db_connect(); // use your own method to connect to your Database

  $result = mysql_query("insert into userResults (date, lat, log, speed, distance, alt, unit, message) values
                         (' ".$date."', '".$lat."', ' ".$log."', ' ".$speed."', ' ".$distance."', ' ".$alt."', ' ".$unit."', ' ".$message."')");
  if (!$result) {
    throw new Exception('Could not register you in database - please try again later.');
  • Guest


Graveyard Database Logo

Has everything you want to know about grave yards. Plus has many celebrites and world leaders graves. Pssst it is my other site

Google + Profile
Check out Android Photo Mapping, its a app/site I been working on

  • wholesale nfl jerseys
  • wholesale sports jerseys