0
votes

Why does this throw a network on main thread exception? its on an async task

class JS extends AsyncTask<StringBuilder, Void, String>{

@Override
protected String doInBackground(StringBuilder... urlBuilder) {
    try {
        URL url = new URL(urlBuilder[0].toString());
        HttpURLConnection client = (HttpURLConnection) url.openConnection();
        client.setRequestProperty("accept", "application/json");
        InputStream in = client.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String returnString = br.readLine();
        client.disconnect();
        return returnString;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

}

EDIT:

Full Code:


        package oliver;
    import android.os.AsyncTask;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import org.json.JSONTokener;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;




    public class DrinkOrDriveWebService {

        private final static String DRINK_OR_DRIVE_WEB_SERVICE = "http://idrivedjango-env-qrs5vkxvvi.elasticbeanstalk.com/api/";

        /**
         * Constructor
         */
        List listOfBarUsers;
        List listOfPartyUsers;
        List listOfParties;
        List listOfPromotions;
        public static JS j = new JS();



        public DrinkOrDriveWebService() {
            listOfBarUsers = new ArrayList();
            listOfPartyUsers = new ArrayList();
            listOfParties = new ArrayList();
            listOfPromotions = new ArrayList();

        }

        public void parseBarUsers() {
            // CPSC 210 Students: You will need to complete this method
            // builds the URL to initialize session in the Waldo API 
            StringBuilder urlBuilder = new StringBuilder(DRINK_OR_DRIVE_WEB_SERVICE);
            urlBuilder.append("/baruser/");
            String input = j.doInBackground((urlBuilder));
            JSONArray obj;
            try {
                // parses the name, location, lat, lon, and timestamp of each Waldo generated
                obj = (JSONArray) (new JSONTokener(input).nextValue());
                System.out.println(obj.toString());
                if (obj.length() != 0) {
                    // For all Waldos generated
                    for (int i = 0, var = obj.length(); i getPartyUsers() {
            return this.listOfPartyUsers;
        }

        public List getBarUsers() {
            return this.listOfBarUsers;
        }

        public List getParties() {
            return this.listOfParties;
        }

        public List getPromos() {
            return this.listOfPromotions;
        }
        /**
         * Return the current list of Waldos that have been retrieved
         * 
         * @return The current Waldos
         */


        /**
         * Retrieve messages available for the user from the Waldo web service
         * 
         * @return A list of messages
         */


        /**
         * Execute a given query 
         * 
         * @param urlBuilder The query with everything but http:
         * @return The JSON returned from the query 
         */


    }
    class JS extends AsyncTask{

        @Override
        protected String doInBackground(StringBuilder... urlBuilder) {
            try {
                URL url = new URL(urlBuilder[0].toString());
                HttpURLConnection client = (HttpURLConnection) url.openConnection();
                client.setRequestProperty("accept", "application/json");
                String returnString = client.getResponseMessage();
                client.disconnect();
                return returnString;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

LogCat:

03-16 11:01:27.375  23401-23401/com.example.untitled4 W/System.err﹕ android.os.NetworkOnMainThreadException
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at java.net.InetAddress.getAllByName(InetAddress.java:214)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseMessage(HttpURLConnectionImpl.java:499)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at oliver.JS.doInBackground(DrinkOrDriveWebService.java:288)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at oliver.DrinkOrDriveWebService.parseParty(DrinkOrDriveWebService.java:146)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.example.untitled4.mthr.doInBackground(mthr.java:20)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.example.untitled4.MyActivity.register(MyActivity.java:75)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.example.untitled4.MyActivity$1.onClick(MyActivity.java:51)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.view.View.performClick(View.java:4438)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.view.View$PerformClick.run(View.java:18422)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5017)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
03-16 11:01:27.385  23401-23401/com.example.untitled4 D/AndroidRuntime﹕ Shutting down VM
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4194bba8)
2
are you call AsynTask().get(), aren't you?Blackbelt
You aren't getting that exception from this code. Post your logcat and maybe the rest of your AsyncTask if you think that's where it is coming from.codeMagic
post the code where you start the asynctaskMarco Acierno
Added a lot more codeooosssososos
It will be good if you refer this question. <a href="stackoverflow.com/questions/6343166/…"> Network On Main Thread</a>Nakul

2 Answers

1
votes

You are invoking the async task the wrong way:

String input = j.doInBackground((urlBuilder));

You should not be calling doInBackground() yourself. Instead, create a new instance of the async task class object and call execute() on it. Capture the results back to UI thread in onPostExecute().

0
votes

For more information regarding NetworkOnMainThreadExecption. Refer this question