Sunday 20 October 2013

Android http connection exception (android.os.NetworkOnMainThreadException)

Problem: android.os.NetworkOnMainThreadException

Here's the error trace:

08-07 22:34:26.657: ERROR/AndroidRuntime(563): Caused by: android.os.NetworkOnMainThreadException
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at java.net.InetAddress.lookupHostByName(InetAddress.java:477)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at java.net.InetAddress.getAllByName(InetAddress.java:249)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:304)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:292)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:274)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1038)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:523)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at maps.test.BaseFeedParser.getInputStream(BaseFeedParser.java:30)
08-07 22:34:26.657: ERROR/AndroidRuntime(563):     at maps.test.DomFeedParser.parse(DomFeedParser.java:23)


Solution: 
There are many solution exists.

1) Use Async Task
or
2) if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }


 Just try out the following if you tried everything and still has the exception  

Remove the android:targetSdkVersion"version_number" from your AndroidManifest.xml
I removed it and my problem solved.








No comments:

Post a Comment