为什么我收到此错误? android.os.NetworkOnMainThreadException

时间:2014-03-16 17:54:45

标签: android

为什么这会在主线程异常上引发网络?它在异步任务上

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;
}

}

编辑:

完整代码:


        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 个答案:

答案 0 :(得分:1)

您正在以错误的方式调用异步任务:

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

您不应该自己致电doInBackground()。相反,创建异步任务类对象的新实例并在其上调用execute()。将结果捕获回onPostExecute()中的UI线程。

答案 1 :(得分:0)

有关NetworkOnMainThreadExecption的更多信息。请参阅此 question