-4

I'm trying to send data to an PHP webservice trough POST from an Android app... It always returns:

FATAL EXCEPTION: main
    Process: com.joaocarreira.familylocator, PID: 1059
    android.os.NetworkOnMainThreadException

Here is my android code:

    String newLat = Float.toString(lat);
    String newLng = Float.toString(lng);
    String newSos = Boolean.toString(sos);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost monitorRequest = new HttpPost("http://localhost/monitor.php");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("currentDateTime", currentDateTime));
    nameValuePairs.add(new BasicNameValuePair("lat", newLat));
    nameValuePairs.add(new BasicNameValuePair("lng", newLng));
    nameValuePairs.add(new BasicNameValuePair("sos", newSos));

    try {
        monitorRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(monitorRequest);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

    nameValuePairs.clear();

Here is my php file:

<?php
require 'connection.php';

$currentDateTime = $_POST["currentDateTime"];
$lat = $_POST["lat"];
$lng = $_POST["lng"];
$sos = $_POST["sos"];

$dbconection = new DBConnect();
$query = "INSERT INTO locationhistory (date, lat, lng, sos) VALUES ('$currentDateTime', '$lat', '$lng', '$sos')";
$dbconection->putData($query);

echo "OK";
?>  
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
jdicarreira
  • 159
  • 2
  • 13

1 Answers1

1

The message says: NetworkOnMainThreadException. In Android applications, one may not execute network code on the Main thread. This means you have to create a separate thread for your code. This can by done via an implementation of the AsyncTaskclass. Look at the documentation

TmKVU
  • 2,910
  • 2
  • 16
  • 30