2016-12-29 40 views
0

所以我有我的AsyncTask問題。如果在doInBackground中捕獲到某個可拋出的錯誤,我需要postExecute來顯示警告對話框。問題是,postExecute永遠不會被調用。我曾嘗試添加@Override,但Android Studio聲稱它不會覆蓋其超類中的某個方法。我也嘗試改變返回類型。我環顧這個網站並找不到答案。提前致謝。onPostExecute不叫

的AsyncTask類

public class AsyncTaskActivity extends AsyncTask<Void, Void, Void> { 

    String exception; 

    @Override 
    protected void onPreExecute() { 
    } 


    protected void onPostExecute() { 
     if (exception.contains("java.net.UnknownHostException")) { 
      MainActivity.showDialog(); 
      Log.i("Error Message", "ERROR MESSAGE SHOWN"); 
     } 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     try { 
      Log.i("AsyncTask", "Loading..."); 
      // Make a URL to the web page. This takes the string representation of the URL 
      // and changes it into a URL object 
      URL url = new URL("http://api.wunderground.com/api/0c0fcc3bf62ab910/conditions/q/IN/Fort_Wayne.json"); 

      // Get the input stream through URL Connection 
      URLConnection con = url.openConnection(); 
      InputStream is = con.getInputStream(); 

      BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

      String line; 
      // read each line and write to text file 
      while ((line = br.readLine()) != null) { 
       Log.i("AsyncTask", line); 
       TextEditor.file = new File(MainActivity.path, "siteInfo.txt"); 
       TextEditor.writeString(line); 
      } 
      TextEditor.saveAndClose(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      exception = e.toString(); 
     } 

     Log.i("AsyncTask", "DONE"); 
     return null; 
    } 
} 

ShowDialog方法

public static void showDialog() { 
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.context); 
    builder.setView(R.layout.dialog_layout); 
    builder.setPositiveButton(
      R.string.dialog_close, 
      new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        System.exit(1); 
       } 
      }); 

    builder.show(); 
} 
+0

看看這個方法簽名對於文檔中的onPostExecute(),您缺少一個參數。 –

+0

其中@Override在onPostExecute中? –

回答

0

看起來已經失去了一些東西

@Override 
protected void onPostExecute(Void result) { 
    super.onPostExecute(result); 
    if (exception.contains("java.net.UnknownHostException")) { 
     MainActivity.showDialog(); 
     Log.i("Error Message", "ERROR MESSAGE SHOWN"); 
    } 
} 
+0

謝謝!你能解釋爲什麼'Void result'有效嗎?我認爲參數是類型結果? – Dusk

+0

從另一個問題的另一個答案引用:OnPostExecute()接受一個參數(從doInBackground()返回的對象)。將其更改爲protected void onPostExecute(Void v)。如果您沒有提供參數,則方法簽名不匹配,並且覆蓋註釋開始抱怨沒有函數可以用此簽名覆蓋。 –

0
@Override 
protected void onPostExecute(Void aVoid) { 
    super.onPostExecute(aVoid); 
    if (exception.contains("java.net.UnknownHostException")) { 
     MainActivity.showDialog(); 
     Log.i("Error Message", "ERROR MESSAGE SHOWN"); 
    } 
} 

請注意,您需要初始化例外,否則可能會引起一個NullPointerException