正常处理异常

时间:2013-08-30 05:42:47

标签: java android android-asynctask

我有一个函数,它发出一个http请求并解析响应json数据。该函数在AsyncTask类中调用。我有一个函数被定义为在调用asynctask之前检查是否存在连接。但是一旦连接检查器函数返回true ...我的函数在asynctask类中运行,并且设备失去连接,应用程序强制关闭。

private void parseJson()
{
    // HTTP request and JSON parsing done here
}

class getData extends AsyncTask <Void,Void,Void>
{


@Override
protected Void onPreExecute(Void...arg0)
{
    super.onPreExecute();
    //progress dialog invoked here
}

@Override
protected Void doInBackground(Void...arg0)
{
    parseJSON();
    return null;
}
@Override
protected Void onPostExecute(Void...arg0)
{
    super.onPostExecute();
    //UI manipulated here
}

}

如何通知用户doInBackground()方法中发生的异常并正确处理异常,因为doInBackground()不允许触发toast消息等事件。

3 个答案:

答案 0 :(得分:3)

这样做

class getData extends AsyncTask <Void,Void,Boolaen>
{


@Override
protected Void onPreExecute(Void...arg0)
{
    super.onPreExecute();
    //progress dialog invoked here
}

@Override
protected Boolaen doInBackground(Void...arg0)
{
    try{ 
          parseJSON();
          return true;
    }catch(Exception e){
      e.printStackStrace();
    }

    return false;
}
@Override
protected Void onPostExecute(Boolaen result)
{
    super.onPostExecute(result);
    if(result){
      //success
    }else{
      // Failure
    } 

    //UI manipulated here
}

}

答案 1 :(得分:2)

我的方法看起来像这样。介绍一个通用的AsyncTaskResult,您可以在其中存储实际返回值(如果需要)或在doInBackground()中发生的异常。在onPostExecute中,您可以检查是否发生了异常并通知您的用户(或处理您的返回值)。

<强> AsyncTaskResult:

public class AsyncTaskResult<T> {
    private T mResult;
    private Exception mException = null;

    public AsyncTaskResult() {
    }

    public AsyncTaskResult(T pResult) {
        this.mResult = pResult;
    }

    public AsyncTaskResult(Exception pException) {
        this.mException = pException;
    }

    public T getResult() {
        return mResult;
    }

    public boolean exceptionOccured() {
        return mException != null;
    }

    public Exception getException() {
        return mException;
    }
}

<强>的AsyncTask:

public class RessourceLoaderTask extends AsyncTask<String, String, AsyncTaskResult<String>> {

    public RessourceLoaderTask() {
    }

    @Override
    protected AsyncTaskResult<String> doInBackground(String... params) {
        try {
            // Checked Exception
        } catch (Exception e) {
            return new AsyncTaskResult<String>(e);
        }
        return new AsyncTaskResult<String>();
    }

    @Override
    protected void onPostExecute(AsyncTaskResult<String> pResult) {
        if (!pResult.exceptionOccured()) {
            //...
        } else {
            // Notify user
        }

    }
}

答案 2 :(得分:0)

getData课程中创建一个字段。在doBackground中设置,在onPostExecute中查看。