2014-07-16 90 views
1

大家好日子。如何處理url.get()失敗

我一直在開發一個應用程序,將數據從網站上的某些表中刪除並顯示在屏幕上。一切都很好,但我想在沒有數據連接的情況下使用冗餘。例如一個對話框或烤麪包簡單地說「沒有數據連接」。

如何以及在哪裏可以放這個?下面是我的Asynctask,其中jsoup獲取數據,所以我假設我可以在這裏放些東西?

目前應用程序崩潰,如果沒有數據連接到網站。

//AsyncTask 
private class Fixtures extends AsyncTask<Void, Void, Void> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     mProgressDialog = new ProgressDialog(MainActivity.this); 
     mProgressDialog.setTitle("Fixtures"); 
     mProgressDialog.setMessage("Loading..."); 
     mProgressDialog.setIndeterminate(false); 
     mProgressDialog.show(); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     try { 
      doc = Jsoup.connect(url).get(); 
      } catch (IOException e) { 

      } 

      tables = doc.select("table"); 

      tablesSize = tables.size(); 

      for (int t = 0; t < (tables.size() - 1); t++){ 
       table = tables.get(t); 
       rows = table.select("tr"); 
       date = doc.select("h2").get(t); 
      } 
     return null; 
    } 

任何幫助或其他答案的方向將非常感激。

回答

0

這應該做到這一點,如果你的任務嵌套在一個片段中,你可以將此方法引入外部類。否則找到一種方法來傳遞應用程序上下文,而不是使用getActivity。這應該是相對線程安全的。

private void buildFailedDialog(){ 

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); 

    dialogBuilder.setMessage("Could Not Connect to Site!"); 
    dialogBuilder.setTitle("Connection Failed"); 

    dialogBuilder.setNegativeButton("OK", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.cancel(); 
     } 
    }); 
    final AlertDialog dialog = dialogBuilder.create(); 
    dialog.show(); 
} 

它可能只是爲了更好地展現敬酒,這樣你就不會從活動

Toast.makeText(getActivity(), "Failed to Connect to Site" ,Toast.LENGTH_LONG).show(); 
+0

感謝加布擾亂用戶。我想烤麪包就足夠了,但是我會在哪裏放?如果我把它放在應用程序中,應用程序仍然崩潰。我需要對文檔進行空檢查嗎?我只是不希望應用程序崩潰,如果它無法訪問該網站。 – Harg

+0

對不起,我錯過了一些東西。這是postExecute崩潰。修正並正確實施敬酒。 – Harg