2014-12-28 6 views
0

웹 사이트에서 일반 텍스트를 가져 오는 기능이 필요한 앱을 만들고 있습니다. 필자는 텍스트를 가져 와서 내 PC에서 인쇄 할 수 있지만 안드로이드 장치에서 실행하려고하면 응용 프로그램이 시작되지 않습니다.Android에서 IO 예외 처리

나는 IOException을 던지는 것과 관련이 있다고 생각한다. 내가 인터페이스를 정의하지 않았기 때문에 나는 그것을하기로되어 있지 않다는 것을 읽었습니다. 이 문제를 해결할 방법이 있습니까? 예외를 throw하지 않으면 Android Studio에서 내 코드를 컴파일하지 않습니다.

기능 :

public String getText(String site) throws IOException { 
    // Make a URL to the web page 
    URL url = new URL(site); 

    // Get the input stream through URL Connection 
    URLConnection con = url.openConnection(); 
    InputStream is =con.getInputStream(); 
    BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

    // read each line and return the final text 
    String res = ""; 
    String line = null; 
    while ((line = br.readLine()) != null) { 
     //System.out.println(line); 
     res += line; 
    } 
    return res; 
} 

그리고 이것은 안드로이드 스튜디오가 나를에서 onCreate 방식으로 실행하게하는 방법이다 :

String text = null; 
    try { 
     text = getText("http://myWebsite.com"); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show(); 
+0

클래식 안티 패턴으로 사용하려고에게 메인 쓰레드

에서 그것을 할 수 없습니다. try 블록의 코드 성공에 의존하는 코드는 동일한 try 블록에 있어야합니다. – EJP

답변

0

먼저 로그 캣 읽기 - 당신은 전체와 거기 예외를 볼 수 stacktrace. 둘째, IOException을 잡는 데는 아무런 문제가 없지만 기능이 문제가 있음을 사용자에게 알리는 것과 같이 캐시 된 후에는 무엇인가해야합니다.

이것이 Android Studio에서 실행되는 방법입니다. 그것 onCreate 방법에서 :

당신이 UI 스레드에서 귀하의 사이트에서 데이터를 받기 때문에 이것은 문제가됩니다, 당신은 작업자 스레드에서 즉, 그것을해야합니다. AsyncTask.

0

는이 문자열을 얻을

class MyTask extends AsyncTask<Void, Void, String>{ 
     private String site; 

     MyTask(String site) { 
      this.site = site; 
     } 

     @Override 
     protected String doInBackground(Void... params) { 
      try { 
       URL url = new URL(site); 
       URLConnection con = url.openConnection(); 
       InputStream is =con.getInputStream(); 
       BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

       // read each line and return the final text 
       String res = ""; 
       String line = null; 
       while ((line = br.readLine()) != null) { 
        //System.out.println(line); 
        res += line; 
       } 
       return res; 
      } catch (IOException e) { 
       e.printStackTrace(); 
      }  
      return null; 
     } 

     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 
      if(s != null){ 
       Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show(); 
      } 
     } 
    } 

new MyTask("http://myWebsite.com").execute()