NetworkOnMainThreadException error in jellybean [duplicate]
Asked Answered
D

2

10

I've been trying to get this to work for the last week or so and still have no idea what the problem is. it works on android 2.1 but not on 4.1. ive got this string in a service that check for updates in my app.

latestVersion = Integer.parseInt(getHttpString(urlLatestVersion));

its called in checkForUpdate(); which is called in onStart(Intent intent, int startId);.

private String getHttpString(String urlString) throws IOException {
            InputStream in = null;
            int response = -1;

            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();

            if (!(conn instanceof HttpURLConnection))
                    throw new IOException("Not an HTTP connection");

            try {
                    HttpURLConnection httpConn = (HttpURLConnection) conn;
                    httpConn.setAllowUserInteraction(false);
                    httpConn.setInstanceFollowRedirects(true);
                    httpConn.setRequestMethod("GET");
                    httpConn.connect();

                    response = httpConn.getResponseCode();
                    if (response == HttpURLConnection.HTTP_OK) {
                            in = httpConn.getInputStream();
                    }
            } catch (Exception ex) {
                    ex.printStackTrace();
                    //
                    //main error currently lies here
                    // TODO fix errors that accures on android 4.0 and above.
                    //
            }
            if (in != null) {
                    StringBuilder sb = new StringBuilder();
                    String line;

                    try {
                            BufferedReader reader = new BufferedReader(
                                            new InputStreamReader(in, "UTF-8"));
                            while ((line = reader.readLine()) != null) {
                                    sb.append(line); // .append("\n");
                            }
                    } finally {
                            in.close();
                    }
                    return sb.toString();
            } else
                    return "";

    }

this is the error from the logcat

W/System.err( 7077): android.os.NetworkOnMainThreadException
W/System.err( 7077):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
W/System.err( 7077):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
W/System.err( 7077):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
W/System.err( 7077):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
W/System.err( 7077):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
W/System.err( 7077):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
W/System.err( 7077):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
W/System.err( 7077):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
W/System.err( 7077):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
W/System.err( 7077):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
W/System.err( 7077):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
W/System.err( 7077):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
W/System.err( 7077):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
W/System.err( 7077):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
W/System.err( 7077):    at com.lukemovement.roottoolbox.pro.Update.getHttpString(Update.java:166)
W/System.err( 7077):    at com.lukemovement.roottoolbox.pro.Update.checkForUpdate(Update.java:98)
W/System.err( 7077):    at com.lukemovement.roottoolbox.pro.Update.onStart(Update.java:75)
W/System.err( 7077):    at android.app.Service.onStartCommand(Service.java:450)
W/System.err( 7077):    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2620)
W/System.err( 7077):    at android.app.ActivityThread.access$1900(ActivityThread.java:143)
W/System.err( 7077):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1306)
W/System.err( 7077):    at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err( 7077):    at android.os.Looper.loop(Looper.java:137)
W/System.err( 7077):    at android.app.ActivityThread.main(ActivityThread.java:4935)
W/System.err( 7077):    at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err( 7077):    at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err( 7077):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
W/System.err( 7077):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
W/System.err( 7077):    at dalvik.system.NativeStart.main(Native Method)
I/Example update( 7077): Invalid int: ""

so has android given up on being backwards compatible or have just just forgotten to add this bit in?

ive read that i need to use AsyncTask. but i cant seem to get it to work for me, could anyone help me with this please?

Deneendenegation answered 13/8, 2012 at 0:36 Comment(2)
As you have probably realized, you need to be asynchronous / multi-threaded. What have you tried? What are you having trouble with?Kersey
made a thread over the hole onStart void. fixed the problem. only just though of it as well.Deneendenegation
A
9

From Android API v15, it requires no heavy process working on main thread. So you should move your logic to another thread like bellow source code:

new Thread(new Runnable() {
   public void run() {
        // your logic
   }                        
}).start();

More information please refer: Responsiveness

Archlute answered 7/9, 2012 at 2:14 Comment(1)
In reply to your answer I just wondering why I got the same exception as this guy. I put my code in Async Task, it launched not in the main thread but in the other thread where I need to hit a button to go to to it. I work with api level 14 and 17.Meson
T
0

just add this code in oncreate on which activity u call Asynck.

code:-

StrictMode.ThreadPolicy policy =
    new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Treed answered 29/5, 2013 at 14:1 Comment(1)
what is the equivalent code for API 8?Pacific

© 2022 - 2024 — McMap. All rights reserved.