2017-04-10 2 views
0

안녕하세요 저는 앱을 만드는 데 Android Studio를 사용하고 있으며 직접 해결할 수없는 오류가 발생했습니다. 내가하고 싶은 것은 URL에서 CSV 파일을 읽고 각 행에 대해 값을지도 표식에 추가하는 것입니다. 나는 쉽게 파일에서 읽어 내 마커로를 추가 할 수 있지만이 URL CSV 읽기는 :(나를 위해 도전을 증명 할 수 있습니다. 을 내 실수하십시오 또는 더 나은 너무 간단하게 할 수있는 것.Java NetworkOnMainThreadException URL에서 csv 파일을 읽습니다.

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

그게 도움이된다면 그것이 작동하는지 테스트하기 위해 이력서에 내에 위치이 코드를()이있다. 이들은 로그 캣에 표시되는 오류입니다.

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. 

답변

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(""); 
관련 문제