2013-08-30 115 views
1

我有一个函数,它会生成一个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()不允许的东西像射击敬酒消息。

回答

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 
} 

} 
0

getData类中做一个字段。将其设置为doBackground,在onPostExecute中检查。

+0

我有点困惑在这里...如果一个异常随时随地抓住了doInBackground()方法没有按内整个AsyncTask类冻结...它是否到达onPostExecute方法? –

+1

@NirajAdhikari检查其他答案,他们有我刚刚简要描述的代码。 –

+0

这种方法对于简单的目的是可以的,但是如果你想从doInBackground中返回一个真正的值而不是“success bool”呢? – Sambuca

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 
     } 

    } 
}