2013-09-26 4 views
0

안드로이드 앱 내부에서 파일을 다운로드하려고합니다. 코드 라인 이르면android에서 파일 다운로드 : Nullpointerexception

connection.connect(); 

로그 캣이 예외를 보여준다

09-23 21:41:21.853: W/System.err(6084): android.os.NetworkOnMainThreadException 
09-23 21:41:21.863: W/System.err(6084):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133) 
09-23 21:41:21.863: W/System.err(6084):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 
09-23 21:41:21.863: W/System.err(6084):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 
09-23 21:41:21.863: W/System.err(6084):  at libcore.io.IoBridge.connect(IoBridge.java:112) 
09-23 21:41:21.863: W/System.err(6084):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 
09-23 21:41:21.863: W/System.err(6084):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 
09-23 21:41:21.863: W/System.err(6084):  at java.net.Socket.connect(Socket.java:842) 
09-23 21:41:21.863: W/System.err(6084):  at libcore.net.http.HttpConnection.<init>(HttpConnection.java:76) 
09-23 21:41:21.873: W/System.err(6084):  at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50) 
09-23 21:41:21.873: W/System.err(6084):  at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340) 
09-23 21:41:21.873: W/System.err(6084):  at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87) 
09-23 21:41:21.873: W/System.err(6084):  at libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 
09-23 21:41:21.873: W/System.err(6084):  at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316) 
09-23 21:41:21.873: W/System.err(6084):  at libcore.net.http.HttpEngine.connect(HttpEngine.java:311) 
09-23 21:41:21.873: W/System.err(6084):  at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290) 
09-23 21:41:21.873: W/System.err(6084):  at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240) 
09-23 21:41:21.873: W/System.err(6084):  at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81) 
09-23 21:41:21.873: W/System.err(6084):  at com.asde.ipac.AsyncUpdater$1.onClick(AsyncUpdater.java:107) 
09-23 21:41:21.883: W/System.err(6084):  at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166) 
09-23 21:41:21.883: W/System.err(6084):  at android.os.Handler.dispatchMessage(Handler.java:99) 
09-23 21:41:21.883: W/System.err(6084):  at android.os.Looper.loop(Looper.java:137) 
09-23 21:41:21.883: W/System.err(6084):  at android.app.ActivityThread.main(ActivityThread.java:5103) 
09-23 21:41:21.883: W/System.err(6084):  at java.lang.reflect.Method.invokeNative(Native Method) 
09-23 21:41:21.883: W/System.err(6084):  at java.lang.reflect.Method.invoke(Method.java:525) 
09-23 21:41:21.893: W/System.err(6084):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
09-23 21:41:21.893: W/System.err(6084):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
09-23 21:41:21.893: W/System.err(6084):  at dalvik.system.NativeStart.main(Native Method) 

로그 캣이 라인 connection.connect이다();

09-23 21:41:21.873: W/System.err(6084):  at com.asde.ipac.AsyncUpdater$1.onClick(AsyncUpdater.java:107) 

이것은 파일의 URL입니다 :

private String urlDownload = "http://192.168.0.107/ipac/ipac.apk/"; 

그리고이 방법의 코드입니다 :

protected void onPostExecute(String lastVer) { 

     PackageInfo packageInfo; 
     try { 
      packageInfo = ((Activity) ctx).getPackageManager().getPackageInfo(ctx.getPackageName(), 0); 
      String currentVer = packageInfo.versionName; 

      System.out.println("Server: "+ lastVer); 
      System.out.println("Installed: "+ currentVer); 
      if(!lastVer.equals(currentVer)) 
      { 
       new AlertDialog.Builder(ctx) 
       .setTitle("UPDATE AVAILABLE") 
       .setMessage("New Test available") 
       .setCancelable(false) 
       .setPositiveButton("DOWNLOAD", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 

         try { 
          System.out.println("0!!!!"); 
           URL url = new URL(urlDownload); 
           System.out.println("0.2!!!!"); 
           URLConnection connection = url.openConnection(); 
           System.out.println("0.3!!!!" + url.toString()); 
           connection.connect(); 
           System.out.println("1!!!!"); 
//        int fileLength = connection.getContentLength(); 

           // download the file 
           InputStream input = new BufferedInputStream(url.openStream()); 
           OutputStream output = new FileOutputStream(path); 
           System.out.println("2!!!!"); 
           byte data[] = new byte[1024]; 
//        long total = 0; 
           int count; 
           while ((count = input.read(data)) != -1) { 
//         total += count; 
//         publishProgress((int) (total * 100/fileLength)); 
            output.write(data, 0, count); 
           } 
           System.out.println("3!!!!"); 
           output.flush(); 
           output.close(); 
           input.close(); 


           //INSTALL 
          } catch (Exception e) { 


           e.printStackTrace(); 
          } 



        } 
       }) 
       .setNegativeButton("LATER", null) 
       .show();  

      } 
     } catch (NameNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 



    } 

무슨 일이 될 수 있는가?

+0

왜 ui 스레드에서 호출되는'onPostexecute'에서 n/w 연산을 수행합니까? – Raghunandan

+0

당신은 onPostExecute에서 당신의 네트워크 일을합니다, 그건 worng way입니다. doInBackground의 모든 네트워크 물건이나 UI 스레드가 아닌 자신의 Thread를하십시오. http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception 그리고이 코드 줄을 제공해주십시오 com.asde.ipac.AsyncUpdater $ 1.onClick (AsyncUpdater.java:132) –

+0

@Raghunandan : 그건' onPostExecute'는'onClick'에 있습니다. (여전히 요점이 있습니다.) – njzk2

답변

0

메인 스레드에서 AsyncTasks 또는 스레드를 사용해야합니다. 그렇지 않으면 Android가 충돌과 유사하게 충돌합니다.

ProgressDialog mProgressDialog; 

는 그런 활동의 (외부에서 OnCreate)을 그 내부를 넣어 :

가에서 onCreate (전역 변수) 이외의 것을 넣어

mProgressDialog = new ProgressDialog(About.this); 
     mProgressDialog.setMessage("Downloading file...."); 
     mProgressDialog.setIndeterminate(false); 
     mProgressDialog.setMax(100); 
     mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 


Then make that class: 
private class DownloadFile extends AsyncTask<String, Integer, String> { 
     @Override 
     protected String doInBackground(String... sUrl) { 

      File folders = new File(Environment.getExternalStorageDirectory() 
        + "/pathofthefile/"); 
      folders.mkdirs(); 

      File file; 
      file = new File(Environment.getExternalStorageDirectory() 
        + "/pathofthefile/nameofthefile.extensionofthefile"); 


      if (!file.exists()) { 
       try { 
        file.createNewFile(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } else { 
       file.delete(); 
       try { 
        file.createNewFile(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 

      try { 
       URL url = new URL(sUrl[0]); 
       URLConnection connection = url.openConnection(); 
       connection.connect(); 
       // this will be useful so that you can show a typical 0-100% 
       // progress bar 
       int fileLength = connection.getContentLength(); 

       // download the file 
       InputStream input = new BufferedInputStream(url.openStream()); 
       OutputStream output = new FileOutputStream(file); 

       byte data[] = new byte[1024]; 
       long total = 0; 
       int count; 
       while ((count = input.read(data)) != -1) { 
        total += count; 
        // publishing the progress.... 
        publishProgress((int) (total * 100/fileLength)); 
        output.write(data, 0, count); 
       } 

       output.flush(); 
       output.close(); 
       input.close(); 
       return "Downloaded"; 
      } catch (Exception e) { 
       return null; 
      } 

     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      mProgressDialog.show(); 
     } 

     @Override 
     protected void onProgressUpdate(Integer... progress) { 
      super.onProgressUpdate(progress); 
      mProgressDialog.setProgress(progress[0]); 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      mProgressDialog.dismiss(); 
      if (result.equals("Downloaded")) { 
       //do something here with the downloaded file 
      } 
     } 
    } 
마지막으로 넣어 그에서 onCreate에서 (또는 다운로드를 호출 할 때) 다운로드 할 파일의 URL을 보내는 AsyncTask 클래스를 호출하려면

DownloadFile downloadFile = new DownloadFile(); 
        downloadFile.execute("http://www.page.com/file.mp3"); 

희망 하시겠습니까?

+1

onPreExecute에서 mProgressDialog를 인스턴스화하지 않는 이유는 무엇입니까? – geekgugi

+0

안녕하세요,이 작품은 나를 위해, 감사합니다! – Hanzo