Java NetworkOnMainThreadException从URL

时间:2017-04-10 16:42:10

标签: java android csv url openstreetmap

你好我正在使用android studio创建一个App,我遇到了一个错误,这个错误很难自己解决。我想要做的就是从网址读取CSV文件,并为每一行将值添加到地图标记。我可以轻松地从文件中读取并添加到我的标记中,但是这个url csv读取对我来说是一个挑战:(。我的错误是什么,甚至更好也可以简化。< / p>

HttpURLConnection conn = null;
    try {
        URL url = new URL("http://www.free-map.org.uk/course/mad/ws/get.php?username=user002&format=csv");
        conn = (HttpURLConnection) url.openConnection();
        InputStream in = conn.getInputStream();
        if(conn.getResponseCode() == 200)
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                String[] comps = inputLine.split(",");
                if (comps.length == 5) {
                    OverlayItem currentItem = new OverlayItem(comps[0], comps[2], new GeoPoint(Double.parseDouble(comps[4]), Double.parseDouble(comps[3])));
                    pois.addItem(currentItem);
                }
            }
        }

    }catch (IOException e){
        new AlertDialog.Builder(this).setMessage("ERROR: "+e).show();
    }
    finally
    {
        if(conn!=null)
            conn.disconnect();
    }

我将此代码放在我的Resume()上,以测试它是否有效,如果有帮助的话。这些是Logcat中显示的错误。

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.edwin.mapping, PID: 2048
                  java.lang.RuntimeException: Unable to resume activity {com.example.edwin.mapping/com.example.edwin.mapping.HelloMap}: android.os.NetworkOnMainThreadException
                      at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
                      at android.app.ActivityThread.access$800(ActivityThread.java:135)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:136)
                      at android.app.ActivityThread.main(ActivityThread.java:5017)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: android.os.NetworkOnMainThreadException
                      at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
                      at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
                      at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
                      at java.net.InetAddress.getAllByName(InetAddress.java:214)
                      at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
                      at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
                      at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
                      at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
                      at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
                      at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
                      at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
                      at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
                      at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:179)
                      at com.example.edwin.mapping.HelloMap.onResume(HelloMap.java:158)
                      at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
                      at android.app.Activity.performResume(Activity.java:5310)
                      at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
                      at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817) 
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250) 
                      at android.app.ActivityThread.access$800(ActivityThread.java:135) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:136) 
                      at android.app.ActivityThread.main(ActivityThread.java:5017) 
                      at java.lang.reflect.Method.invokeNative(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:515) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
                      at dalvik.system.NativeStart.main(Native Method) 
Application terminated.

1 个答案:

答案 0 :(得分:2)

使用Async Task执行网络操作。不要在UI线程上运行它。

例如:

private class ReadFile extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
       HttpURLConnection conn = null;
        try {
            URL url = new URL("http://www.free-map.org.uk/course/mad/ws/get.php?username=user002&format=csv");
            conn = (HttpURLConnection) url.openConnection();
            InputStream in = conn.getInputStream();
            if(conn.getResponseCode() == 200)
            {
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String inputLine;
                while ((inputLine = br.readLine()) != null) {
                    String[] comps = inputLine.split(",");
                    if (comps.length == 5) {
                        OverlayItem currentItem = new OverlayItem(comps[0], comps[2], new GeoPoint(Double.parseDouble(comps[4]), Double.parseDouble(comps[3])));
                        pois.addItem(currentItem);
                    }
                }
            }

        }catch (Exception e){
            Log.e("Error, e.toString());
        }
        finally
        {
            if(conn!=null)
                conn.disconnect();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {

    }

    @Override
    protected void onPreExecute() {}
}

现在使用:

调用它
new ReadFile().execute("");