1

I am trying to pass my location on my web service from my android app. But i have now is errors like this.

LogCat:

02-24 21:37:35.438: E/AndroidRuntime(657): FATAL EXCEPTION: main
02-24 21:37:35.438: E/AndroidRuntime(657): android.os.NetworkOnMainThreadException
02-24 21:37:35.438: E/AndroidRuntime(657):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
02-24 21:37:35.438: E/AndroidRuntime(657):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
02-24 21:37:35.438: E/AndroidRuntime(657):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
02-24 21:37:35.438: E/AndroidRuntime(657):  at libcore.io.IoBridge.connect(IoBridge.java:112)
02-24 21:37:35.438: E/AndroidRuntime(657):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
02-24 21:37:35.438: E/AndroidRuntime(657):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
02-24 21:37:35.438: E/AndroidRuntime(657):  at java.net.Socket.connect(Socket.java:842)
02-24 21:37:35.438: E/AndroidRuntime(657):  at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
02-24 21:37:35.438: E/AndroidRuntime(657):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
02-24 21:37:35.438: E/AndroidRuntime(657):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-24 21:37:35.438: E/AndroidRuntime(657):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-24 21:37:35.438: E/AndroidRuntime(657):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
02-24 21:37:35.438: E/AndroidRuntime(657):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
02-24 21:37:35.438: E/AndroidRuntime(657):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-24 21:37:35.438: E/AndroidRuntime(657):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
02-24 21:37:35.438: E/AndroidRuntime(657):  at com.example.projectthesis.JSONParser.makeHttpRequest(JSONParser.java:51)
02-24 21:37:35.438: E/AndroidRuntime(657):  at com.example.projectthesis.LocationGetter.onLocationChanged(LocationGetter.java:138)
02-24 21:37:35.438: E/AndroidRuntime(657):  at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:234)
02-24 21:37:35.438: E/AndroidRuntime(657):  at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:167)
02-24 21:37:35.438: E/AndroidRuntime(657):  at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:183)
02-24 21:37:35.438: E/AndroidRuntime(657):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-24 21:37:35.438: E/AndroidRuntime(657):  at android.os.Looper.loop(Looper.java:137)
02-24 21:37:35.438: E/AndroidRuntime(657):  at android.app.ActivityThread.main(ActivityThread.java:4424)
02-24 21:37:35.438: E/AndroidRuntime(657):  at java.lang.reflect.Method.invokeNative(Native Method)
02-24 21:37:35.438: E/AndroidRuntime(657):  at java.lang.reflect.Method.invoke(Method.java:511)
02-24 21:37:35.438: E/AndroidRuntime(657):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-24 21:37:35.438: E/AndroidRuntime(657):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-24 21:37:35.438: E/AndroidRuntime(657):  at dalvik.system.NativeStart.main(Native Method)

**

I've put my web passing code to onLocationChange section and here it is:

LocationGetter:

public class LocationGetter extends MapActivity implements LocationListener { // <1>
    private static final String TAG = "LocationActivity";
        LocationManager locationManager; // <2>
    Geocoder geocoder; // <3>
    TextView locationText;
    MapView map;
    MapController mapController; // <4>

// Progress Dialog
private ProgressDialog pDialog;
//JSONParser Object creation
JSONParser jsonParser = new JSONParser();
// url to pass location to web
//private static String url_create_product = "http://student-thesis.netii.net/location_adding.php";
private static String url_create_product = "http://10.0.2.2/TheCalling/location_adding.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.maps);
    locationText = (TextView) this.findViewById(R.id.lblLocationInfo);
    map = (MapView) this.findViewById(R.id.mapview);
    map.setBuiltInZoomControls(true);
    mapController = map.getController(); // <4>
    mapController.setZoom(19);
    locationManager = (LocationManager) this
            .getSystemService(LOCATION_SERVICE); // <2>
    geocoder = new Geocoder(this); // <3>
    Location location = locationManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); // <5>
    if (location != null) {
        Log.d(TAG, location.toString());
        this.onLocationChanged(location); // <6>
    }
}
@Override
protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            60000, 5, this); // <7>
}
@Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this); // <8>
}
@Override
public void onLocationChanged(Location location) { // <9>
    Log.d(TAG, "onLocationChanged with location " + location.toString());
    String text = String.format(
            "Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f \n",
            location.getLatitude(), location.getLongitude(),
            location.getAltitude(), location.getBearing());
    this.locationText.setText(text);
    try {
        List<Address> addresses = geocoder.getFromLocation(
                location.getLatitude(), location.getLongitude(), 10); // <10>
        for (Address address : addresses) {
            this.locationText.append(" " + address.getAddressLine(0));
        }
        int latitude = (int) (location.getLatitude() * 1000000);
        int longitude = (int) (location.getLongitude() * 1000000);      

        GeoPoint point = new GeoPoint(latitude, longitude);
        mapController.animateTo(point); // <11>

        List<Overlay> mapOverlays = map.getOverlays();
        Drawable drawable = this.getResources().getDrawable(R.drawable.reddot);
        AddItemizedOverlay itemizedOverlay =
        new AddItemizedOverlay(drawable, this);

        OverlayItem overlayitem = new OverlayItem(point, "Hello", "Sample Overlay item");

        itemizedOverlay.addOverlay(overlayitem);
        mapOverlays.add(itemizedOverlay);

        String strLatitude = Integer.toString(latitude);
        String strLongitude = Integer.toString(longitude);

        //Building parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("latitude", strLatitude));
        params.add(new BasicNameValuePair("longitude", strLongitude));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

        // check log cat fro response
        Log.d("Create Response", json.toString());

        try {
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // successfully updated
                Toast.makeText(getBaseContext(), "Location Passing successful", Toast.LENGTH_SHORT).show();
            } else {
                // failed to create product
                Toast.makeText(getBaseContext(), "Location Passing Unsuccessful", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    } catch (IOException e) {
        Log.e("LocateMe", "Could not get Geocoder data", e);
    }
}
@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
}
@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}
}

How can I deal with this?

MakAdin
  • 41
  • 1
  • 1
  • 7

4 Answers4

1

In your onLocationChanged start a custom AsyncTask and put in his doInBackground method all the code using an http connection like jsonParser.makeHttpRequest.

Then in the method postExecute of the AsyncTask you should update the data and/or the ui.

Alessandro Alessandra
  • 1,065
  • 12
  • 18
1

OMG. Do not allow network operations on your main thread. Unless, of course, you want your users to hate you.

An AsyncTask works OK, although I think you would get better results by using a background Service (IntentService). That decouples your location uploads from your foreground, which would allow you to cache updates, etc.

Also, I notice that you're not checking that you have network connectivity before you try to send data. It only seems that the tubez is ubiquitious :).

Joe Malin
  • 8,621
  • 1
  • 23
  • 18
  • Well... Guys, what i am trying to do in my application is this. Every time that my location will change it will be automatically send to my web service and to my database. So i guess i need to put the passing of data to my web onto an async task section. i will try to revise my codes. Thank you guys. – MakAdin Feb 24 '13 at 04:27
0

I had an exception like that as well with my web service. It happened because I did not do the web service call inside of an asynchronous task private class. You should try putting the code inside that class so it does not cause a timeout over the network.

If this does not help I will remove my answer. I don't want to have a bad answer as the only on. Just comment

Mark
  • 911
  • 13
  • 30
0

See this question here. You cannot have a network operation on the main thread. Either as Mark sed wrap it on and AsyncTask

OR (And this is not recommendable)

you can allow network operations in your main thread. That is not good because it will lock your UI giving the user a bad experience.

StrictMode.ThreadPolicy policy = new StrictMode. ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy);
Community
  • 1
  • 1
caiocpricci2
  • 7,714
  • 10
  • 56
  • 88
  • So if any of the answers above helped, please mark it as correct. If i didn't answer your own question and mark it as correct, so this question can be marked as resolved! – caiocpricci2 Feb 25 '13 at 10:44