TAGS :Viewed: 9 - Published at: a few seconds ago

[ Reading data from a JSON url but android doesn't allow it. NetworkOnMainThread exception and StrictMode$AndroidBlockGuardPolicy error ]

I'm trying to use Google Map in Android Application. MainActivity contains EditText, ImageButton and MapView. When user gives some query and taps ImageButton, MainAcitivity is supposed to get some JSON data from a url and then I need to use that JSON data to create Markers and dialogBox when user clicks those Markers. Whenever I run the application, it runs fine. But when I click ImageButton, application stops giving logcat error NetworkOnMainThreadException and StrickMode$AndroidBlockGuardPolicy. I've attached logcat output and MainActivity. I've run this JSON program creating other test project and it is working just fine. But when I add it to MainAcitivity, it doesn't work. I believe, android's security policies are stopping it from getting data from url.

So what is the reason of this error and how can I make this Activity work? Thank You very much friends for paying attention. Tell me if you need more code for CustomOverlayItem object or JSON object.

public class MainActivity extends MapActivity {

        private List<Home> listHome = new ArrayList<Home>();

        @Override
        public void onCreate(Bundle savedInstanceState) {

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

            MapView mv_map = (MapView) findViewById(R.id.mv_map);
            MapController mapController = mv_map.getController();
            mv_map.setBuiltInZoomControls(true);
            mapController.setZoom(5);
            Markers markers = new Markers(this.getResources().getDrawable(
                    R.drawable.ic_action_home), this);
            CustomOverlayItem items = new CustomOverlayItem(getuserLocation(),
                    "Checking", "Checking");
            List<Overlay> overlays = mv_map.getOverlays();
            markers.addOverlayItem(items);
            overlays.add(markers);

            ImageButton ib_search = (ImageButton) findViewById(R.id.ib_search);
            ib_search.setOnClickListener(new OnClickListener() {

            @Override
                public void onClick(View v) {
                    Json json = new Json();
                    listHome = json.getListHome();
                    EditText editText = (EditText) findViewById(R.id.et1_search);
                    editText.setText(listHome.get(0).getTitle().toString());
                }
            });

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }

        @Override
        protected boolean isRouteDisplayed() {
            return false;
        }

        private GeoPoint getuserLocation() {
                GeoPoint geoPoint = new GeoPoint(19240000, -99120000);
            return geoPoint;
        }
    }

Logcat Output : errors

08-04 16:26:55.253: E/Trace(1307): error opening trace file: No such file or directory (2)
08-04 16:26:57.743: E/MapActivity(1307): Couldn't get connection factory client
08-04 16:27:01.643: E/AndroidRuntime(1307): FATAL EXCEPTION: main
08-04 16:27:01.643: E/AndroidRuntime(1307): android.os.NetworkOnMainThreadException
08-04 16:27:01.643: E/AndroidRuntime(1307):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at java.net.URL.openStream(URL.java:462)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at com.incubers.map.json.Json.getListHome(Json.java:33)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at com.incubers.map.MainActivity$1.onClick(MainActivity.java:53)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at android.view.View.performClick(View.java:4084)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at android.view.View$PerformClick.run(View.java:16966)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at android.os.Handler.handleCallback(Handler.java:615)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at android.os.Looper.loop(Looper.java:137)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at android.app.ActivityThread.main(ActivityThread.java:4745)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at java.lang.reflect.Method.invokeNative(Native Method)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at java.lang.reflect.Method.invoke(Method.java:511)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-04 16:27:01.643: E/AndroidRuntime(1307):     at dalvik.system.NativeStart.main(Native Method)

Answer 1


NetworkOnMainThreadException exception is thrown when an application attempts to perform a network operation on its main thread.use AsyncTask,Handler,HandlerThread for gettting Json from Server

Answer 2


StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    .detectAll()
    .penaltyLog()
    .penaltyDialog()
    .build());

refer this

You can also avoid IO related tasks on main thrread/

Use Handler,AsyncTask and post result on UI.