1

I am using osmdroid bonuspack in my android application, when I run the code I get this error NetworkOnMainThread Exception.

this is my code:

public class MainActivity extends Activity {
    private MapView myOpenMapView;
    private MapController mapController;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);  

            RoadManager roadManager = new OSRMRoadManager();

            myOpenMapView = (MapView) findViewById(R.id.openmapview);
            myOpenMapView.setTileSource(TileSourceFactory.MAPNIK);
            GeoPoint startPoint = new GeoPoint(48.13, -1.63);
           MapController mapController = myOpenMapView.getController();
            mapController.setCenter(startPoint);
            mapController.setZoom(9);
            ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
            waypoints.add(startPoint);
            waypoints.add(new GeoPoint(48.4, -1.9)); //end point
            Road road = roadManager.getRoad(waypoints);
            PathOverlay roadOverlay = RoadManager.buildRoadOverlay(road, myOpenMapView.getContext());
            myOpenMapView.getOverlays().add(roadOverlay);
            myOpenMapView.invalidate();
         //   RoadManager roadManager = new MapQuestRoadManager();
            roadManager.addRequestOption("routeType=bicycle");


            final ArrayList<ExtendedOverlayItem> roadItems = 
                      new ArrayList<ExtendedOverlayItem>();
                    ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes = 
                      new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, roadItems, myOpenMapView);
                    myOpenMapView.getOverlays().add(roadNodes);

                     Drawable marker = getResources().getDrawable(R.drawable.marker);
                        for (int i=0; i<road.mNodes.size(); i++){
                                RoadNode node = road.mNodes.get(i);
                                ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem("Step "+i, "", node.mLocation, this);
                                nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
                                nodeMarker.setMarker(marker);
                                roadNodes.addItem(nodeMarker);

                        nodeMarker.setDescription(node.mInstructions);
                        nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
                        Drawable icon = getResources().getDrawable(R.drawable.ic_launcher);
                        nodeMarker.setImage(icon);

                        }

}}

and this is the logCat:

11-11 04:00:01.916: E/AndroidRuntime(1040): FATAL EXCEPTION: main
11-11 04:00:01.916: E/AndroidRuntime(1040): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.openstreetbonus/com.example.openstreetbonus.MainActivity}: android.os.NetworkOnMainThreadException
11-11 04:00:01.916: E/AndroidRuntime(1040):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at android.os.Looper.loop(Looper.java:137)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at java.lang.reflect.Method.invokeNative(Native Method)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at java.lang.reflect.Method.invoke(Method.java:525)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at dalvik.system.NativeStart.main(Native Method)
11-11 04:00:01.916: E/AndroidRuntime(1040): Caused by: android.os.NetworkOnMainThreadException
11-11 04:00:01.916: E/AndroidRuntime(1040):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at org.osmdroid.bonuspack.utils.HttpConnection.doGet(HttpConnection.java:75)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at org.osmdroid.bonuspack.routing.OSRMRoadManager.getRoad(OSRMRoadManager.java:204)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at com.example.openstreetbonus.MainActivity.onCreate(MainActivity.java:46)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at android.app.Activity.performCreate(Activity.java:5133)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-11 04:00:01.916: E/AndroidRuntime(1040):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)

I followed the tutorial at this site: https://code.google.com/p/osmbonuspack/wiki/Tutorial_1

scai
  • 20,297
  • 4
  • 56
  • 72
ruaa.brkat
  • 41
  • 1
  • 8

3 Answers3

2

You should use async task for network request. This link will help you to write Async Tasks

Sanket Shah
  • 4,352
  • 3
  • 21
  • 41
diordna
  • 550
  • 5
  • 14
0

Since the inception of Android Honeycomb, in order to make apps more responsive, it was disallowed to use networking tasks to be performed on the "main" thread or the "ui" thread. As you are trying to perform network operations on the "main" thread itself, Android throws an exception sweetly named NetworkOnMainThreadException.

To workaround this issue, you can either use:- AsyncTask, a worker thread (by extending Thread class, or use Handlers

You can use AsyncTask when you want to make UI changes after the network connection is closed or update the UI as the network connection is in progress.

Threads are better if you dont have any UI updations.

d3m0li5h3r
  • 1,957
  • 17
  • 33
0

You should avoid performing long running operations on the UI thread. This includes file and network access.

StrictMode allows to setup policies in your application to avoid doing incorrect things. For example the following setup will crash your application if it violates some of the Android policies. StrictMode should only be used during development and not in your live application.

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    .detectAll().penaltyLog().penaltyDeath().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
    .penaltyLog().penaltyDeath().build());

Try out as below :

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main);       
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}
GrIsHu
  • 29,068
  • 10
  • 64
  • 102