2013-10-06 5 views
0

이 코드를 사용하여 URL을 요청하고 TextView로 결과를 화면에 표시합니다. 이건 내 코드입니다 :은 android에서 URL을 요청할 수 없을 때 오류 메시지를 표시합니다.

public class AsyncronoustaskAndroidExample extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.asyncronoustask_android_example);   
    final Button GetServerData = (Button) findViewById(R.id.GetServerData);   

    GetServerData.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      String serverURL = "http://androidexample.com/media/webservice/getPage.php"; 
      new LongOperation().execute(serverURL); 

     } 
    }); 

} 

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

    private final HttpClient Client = new DefaultHttpClient(); 
    private String Content; 
    private String Error = null; 
    private ProgressDialog Dialog = new ProgressDialog(AsyncronoustaskAndroidExample.this); 
    TextView uiUpdate = (TextView) findViewById(R.id.output); 
    protected void onPreExecute() {   
     uiUpdate.setText("Output : "); 
    } 
    protected Void doInBackground(String... urls) { 
     try {        

      // Server url call by GET method 
      HttpGet httpget = new HttpGet(urls[0]); 
      ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
      Content = Client.execute(httpget, responseHandler); 

     } catch (ClientProtocolException e) { 
      Error = e.getMessage(); 
      cancel(true); 
     } catch (IOException e) { 
      Error = e.getMessage(); 
      cancel(true); 
     }   
     return null; 
    } 

    protected void onPostExecute(Void unused) { 
     // NOTE: You can call UI Element here. 

     if (Error != null) { 

      uiUpdate.setText("Output : "+Error); 

     } else { 

      uiUpdate.setText("Output : "+Content); 

     } 
    } 

} 

}

그러나 URL이 무효 인 경우에, 내 프로그램 중지, 나는 오류 메시지를 보여 주려고하지만 난 할 수 없습니다. 도와주세요!

감사합니다.

+0

프로그램 중단으로 무엇을 의미합니까? – edisonthk

답변

0

로그 고양이를 확인하십시오. 대부분 IllegalStateException을 가져야합니다. 만약 그렇다면 당신도 그것을 잡아야합니다.

0

URL을 확인하려면 유효하거나 유효하지 않은 URL을 사용해야합니다. 여기에 예제가 있습니다.

URL url; 
try { 
    url = new URL(urls[0]); 
    HttpGet httpGet = new HttpGet(url.toString()); 

} catch (MalformedURLException e1) {      
    e1.printStackTrace(); 
} 
관련 문제