1

Asynctaskメソッドは次のとおりです。

public class Read extends AsyncTask<String, Integer, String> {
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {
            sUrl = sUrl.trim();
            json = lastTweet(sUrl);
            return json.getString(params[0]);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub 
    }

}

関連する lastTweet メソッド:

public JSONObject lastTweet(String username)
        throws ClientProtocolException, IOException, JSONException {
    HttpGet get = new HttpGet(url.toString());
    HttpResponse r = client.execute(get);
    int status = r.getStatusLine().getStatusCode();
    if (status == 200) {
        HttpEntity e = r.getEntity();
        String data = EntityUtils.toString(e);
        JSONArray timeline = new JSONArray(data);
        JSONObject last = timeline.getJSONObject(0);
        return last;
    }
}

このコードはすべて正常に動作しています。今のところ問題ありません。しかし、私がやりたい小さないじりがあります。HTTP 転送中に接続が失われると、RemoteException がスローされ、アプリがクラッシュします。

メソッド内で例外を処理しようとしましたが、処理Asyncできませんでした。

そのような例外を処理する方法はありますか?

4

1 に答える 1

1

実行する前にネットワーク接続を確認できますRead AsyncTask

1.接続を確認する

if(ifConnectionIsAvailable)
    new Read().execute();

2. 接続タイムアウトを設定する

HttpGet get = new HttpGet(url.toString());
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;// in milliseconds 
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse r = httpClient.execute(get);
于 2013-07-14T19:54:15.650 に答える