2017-07-05 89 views
0

我似乎无法正确处理异常。这是我的异步方法:无法处理由AsyncTask调用的方法中的异常

private class PostData extends AsyncTask<String, Void, Void> 
    { 
     String response; 
     protected void onPreExecute() 
     { 
      apply.setText("APPLYING..."); 
     } 
     @Override 
     protected Void doInBackground(String... params) { 

      try { 
       SendHTTPData sendHTTPData = new SendHTTPData(); 
       response = sendHTTPData.sendData(params); 
      } 
      catch(Exception e) 
      { 
       Log.e("someTag", "Caught exception after doinbackground"); 
       response = "ERROR!"; 
      } 
       return null; 
     } 
     protected void onPostExecute() 
     { 
      apply.setText(response); 
     } 
} 

现在,每当sendData方法被调用,它返回无论是一个“错误”或“应用”的字符串,但是当网页关闭,产生异常的ConnectException和SQLite异常然后我的按钮卡在“APPLYING”状态。

我想在sendData方法中出现错误时将按钮文本设置为“ERROR”。

这里是我sendHTTPData类以防万一:

public class SendHTTPData { 

    public String sendData(String...) 
    { 
     String POST_DATA = "switch=" + sw + ... 
      try { 
       URL update = new URL(Utils.WEB_URL+path+"?"+POST_DATA); 
       BufferedReader in = new BufferedReader(
         new InputStreamReader(update.openStream())); 

       String inputLine; 
       while ((inputLine = in.readLine()) != null) {} 
       in.close(); 
       Log.w("someTag", "DONE GET RESPONSE"); 
       if(inputLine=="1") 
        return "APPLIED"; 
       else 
        return "ERROR"; 
      } 
      catch (Exception e) { 
       Log.e("someTag", "ERROR BC OF EXCEPTION"); 
       return "ERROR"; 
      } 

     } 
} 

回答

2

onPostExecute是不正确的,所以它可能永远不会得到所谓的它应该看起来像

@Override 
protected void onPostExecute(Void param) 
{ 
    apply.setText(response); 
} 

理想情况下,你应该把你的回应到您的onPostExecute,因为这是您使用它的地方,所以一切应该看起来像这样

private class PostData extends AsyncTask<String, Void, String> 
    { 
     protected void onPreExecute() 
     { 
      apply.setText("APPLYING..."); 
     } 
     @Override 
     protected String doInBackground(String... params) { 
      String response; 
      try { 
       SendHTTPData sendHTTPData = new SendHTTPData(); 
       response = sendHTTPData.sendData(params); 
      } 
      catch(Exception e) 
      { 
       Log.e("someTag", "Caught exception after doinbackground"); 
       response = "ERROR!"; 
      } 
       return response; 
     } 
     @Override 
     protected void onPostExecute(String response) 
     { 
      apply.setText(response); 
     } 
} 
+0

如何使用doInBackground在无效返回类型时返回字符串?此外,代码不起作用,我试了一下。 – Harsh

+0

您通过在这里更改值来返回字符串'AsyncTask '最后一个字符串用于返回类型。你应该阅读关于AsyncTasks – tyczj

+0

的文档。我还编辑了我的答案以返回一个字符串 – tyczj