0

我有这段代码来请求一个 URL 并通过 TextView 在屏幕上显示结果。这是我的代码:

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 无效时,我的程序停止,我试图显示错误消息但我不能。请帮我!

非常感谢。

4

2 回答 2

0

如果您想检查您的 url 是否有效,您需要使用 URL。这是示例。

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

} catch (MalformedURLException e1) {                    
    e1.printStackTrace();
}
于 2013-10-06T05:02:18.600 回答
0

请检查您的日志猫。大多数情况下,您必须得到一个 IllegalStateException。如果是这种情况,你也必须抓住它。

于 2013-10-06T04:56:57.867 回答