2013-04-26 3 views
2

인터넷 txt 파일의 콘텐츠를 가져오고 싶습니다. 에뮬레이터로 열면이 메시지가 나타납니다.URL에서 파일 읽기

"불행히도 응용 프로그램이 중지되었습니다."

"http : //"를 제거해도 아무 것도 읽지 않고 아무런 변화가 없으며 null이됩니다. 뭐가 문제 야? 위의 URL을 어떻게 읽을 수 있습니까? 권한을 추가했습니다.

이 코드는 변경되었지만 여전히 동일한 오류가 발생합니다. 내가 실수 한거야? http://dforum.zxq.net/code.txt

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
new AsyncTask<Void, Void, Void>() { 

     @Override 
     protected Void doInBackground(Void... arg0) { 



      try { 
       URL url = new URL("http://dforum.zxq.net/myfile.txt"); 

       BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
       String str; 
       while ((str = in.readLine()) != null) { 
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();  
        // str is one line of text; readLine() strips the newline character(s) 
       } 
       in.close(); 
      } catch (MalformedURLException e) { 
      } catch (IOException e) { 
      } 




      return null; 
      // TODO Auto-generated method stub 

     } 


    }.execute(); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

}

+0

으로 바꾸십시오. logcat 출력을 추가하십시오. – rekire

+0

http://dforum.zxq.net/log.txt –

답변

1

것은 당신이 UI 스레드에서 그렇게하고 또한 인터넷 권한이 있는지 확인하지 않습니다 있는지 확인하십시오.

두 경우 모두 앱이 고장 나게하는 예외가 발생할 수 있습니다.

new AsyncTask<Void, Void, Void>{ 
    @Override 
    protected Void doInBackground(Void... params) { 

     // add your try catch block here. 

     return null; 
    } 
}.execute(); 
+0

허가 <권한 안드로이드 : 이름 = "android.permission.INTERNET은"> <사용 - 권한 안드로이드 : 이름 = "android.permission .INTERNET "/> –

+0

이것은 내 부름이다. 그러나 whats ui thread는 모른다. 나는 아직도이 eror을 얻는다 –

+0

그것은 스레딩 물건 일 것이다. try catch 블록을 비동기 태스크에 랩핑하십시오. 나는 그 대답을 잠시 기다려주십시오. – rekire

0

당신이 AsyncTask 내부를 실행하여 메인 UI 스레드 떨어져이 과정을 복용해야합니다 : 여기

는 GUI 스레드에서 일을하고, 네트워크 운영을 방지하는 방법에 대한 예입니다. 이 자습서 : http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/을 확인하십시오. 더 구체적으로 JSONParser 클래스를 살펴보십시오.

UPDATE 당신은 내가이 충돌하는 것 이유라고 생각 while 루프에서 Toast 호출

. Log.d() 또는 System.out.println()

+0

)이 말을 모두 추가했습니다. 위의 코드 전체를 작성 했습니까? 그래서 왜 다시 닫혔습니까? –

+0

다른 경우 로그 출력으로 응답을 업데이트하십시오. –

+0

위의 링크 된 자습서 에서처럼 AsyncTask에 대한 내부 클래스를 만들어보십시오. –