2013-11-02 120 views
0

我使用Asynctask從網絡中提取一些數據並在進一步的計算中使用它。我也實現了連接檢查,如果沒有連接,它將返回false,但如果有互聯網連接和「服務器關閉」,則會崩潰。我想顯示一個對話框來通知用戶他們的互聯網遇到了問題。但我似乎無法做到。請幫忙。提前致謝。 :)應用程序在網絡問題/服務器崩潰時崩潰

HttpClient client; 
String URL, re, element; 
JSONObject json, getjson; 
int i, j, statusCode; 
HttpGet httpget; 
HttpResponse response; 
HttpEntity entity; 
InputStream is; 
BufferedReader reader; 
StringBuilder sb, sb1; 

SharedPreferences getinput, passjson; 
ProgressDialog pd; 
Context context = DataRetrieve.this; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 

    super.onCreate(savedInstanceState); 

    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
      WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    setContentView(R.layout.dataretrieve); 
    // Bundle gotBasket = getIntent().getExtras(); 
    // URL = gotBasket.getString("key"); 
    getinput = getSharedPreferences("input", 0); 
    URL = getinput.getString("key", null); 

    if (!isNetworkReachable()) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(context); 
     builder.setTitle("No Network Connection"); 
     builder.setMessage("The Network is unavailable. Please check your internet connection."); 
     builder.setPositiveButton("Settings", 
       new DialogInterface.OnClickListener() { 

        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         // TODO Auto-generated method stub 
         Intent m = new Intent(
           android.provider.Settings.ACTION_SETTINGS); 
         startActivity(m); 
        } 
       }); 
     builder.setNegativeButton("Cancel", 
       new DialogInterface.OnClickListener() { 

        @Override 
        public void onClick(DialogInterface arg0, int arg1) { 
         // TODO Auto-generated method stub 
         Intent n = new Intent(DataRetrieve.this, 
           OpTilt.class); 
         startActivity(n); 
        } 
       }); 

     builder.create().show(); 
    } else { 
     Read r = new Read(); 
     r.execute(); 

    } 

} 

private boolean isNetworkReachable() { 
    // TODO Auto-generated method stub 
ConnectivityManager mManager = (ConnectivityManager) context 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo current = mManager.getActiveNetworkInfo(); 
    if (current != null && current.isConnectedOrConnecting()) { 
     return true; 
    } 

    return false; 
} 

public class Read extends AsyncTask<String, Integer, String> { 
    @Override 
    protected void onPreExecute() { 

     pd = new ProgressDialog(DataRetrieve.this); 
     pd.setTitle("Processing..."); 
     pd.setMessage("Please wait."); 
     pd.setCancelable(false); 
     pd.setIndeterminate(true); 
     pd.show(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     // TODO Auto-generated method stub 
     re = null; 
     is = null; 
     json = null; 
     try { 

      httpget = new HttpGet(URL); 
      client = new DefaultHttpClient(); 
      response = client.execute(httpget); 
      entity = response.getEntity(); 
      is = entity.getContent(); 
      statusCode = response.getStatusLine().getStatusCode(); 

     } catch (Exception e) { 

      statusCode = -1; 
      Log.e("log_tag", "Erro http " + e.toString()); 
     } 
     if (statusCode == 200) { 

      try { 
       reader = new BufferedReader(new InputStreamReader(is, 
         "UTF-8"), 8); 
       sb = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) { 
        sb.append(line + "\n"); 
       } 
       is.close(); 
       re = sb.toString(); 

      } catch (Exception e) { 
       Log.e("log_tag", "Erro conversão " + e.toString()); 
      } 

     } 
     return re; 

    } 

    @Override 
    protected void onPostExecute(String result) { 
     // TODO Auto-generated method stub 
     pd.dismiss(); 
     try { 

      json = new JSONObject(result); 
      getjson = json.getJSONObject("Solar"); 
      String H[] = new String[getjson.length()]; 
      for (i = 0, j = 1; i < getjson.length(); i++, j++) { 
       H[i] = getjson.getString("" + j); 

      } 
      SharedPreferences sendHm; 
      sendHm = getSharedPreferences("parsedata", 0); 
      SharedPreferences.Editor editor = sendHm.edit(); 
      for (int k = 0; k < H.length; k++) { 
       editor.putString("Hm" + k, H[k]); 
      } 
      editor.commit(); 
      Intent f = new Intent(DataRetrieve.this, Calculator.class); 
      startActivity(f); 
      /* 
      * Bundle bundle = new Bundle(); bundle.putStringArray("key1", 
      * H); Intent f = new Intent(DataRetrieve.this, 
      * Calculator.class); f.putExtras(bundle); startActivity(f); 
      */ 

     } 

     catch (JSONException e) { 
      Log.e("log_tag", "Erro dados " + e.toString()); 
     } 

    } 
} 

@Override 
protected void onPause() { 
    // TODO Auto-generated method stub 
    super.onPause(); 
    finish(); 
} 

} 
+1

什麼'錯了嗎?你有什麼錯誤嗎?所有相同的else-if isNetworkReachable()中的分支不是必需的 – Blackbelt

+0

你說得對,我會刪除它。問題是它只檢測網絡是否啓用。我想檢查網絡是否工作正常。當網絡出現故障時,應用程序會顯示一個進度條,然後崩潰。 – renupok92

+0

我編輯了代碼並刪除了else-if分支。但我的問題依然存在。 – renupok92

回答

1

改變你的postExcute方法的代碼下面(你應該檢查結果不爲空或空)

pd.dismiss(); 
    if(!TextUtils.isEmpty(result)) 
    { 

    try { 

     json = new JSONObject(result); 
     getjson = json.getJSONObject("Solar"); 
     String H[] = new String[getjson.length()]; 
     for (i = 0, j = 1; i < getjson.length(); i++, j++) { 
      H[i] = getjson.getString("" + j); 

     } 
     SharedPreferences sendHm; 
     sendHm = getSharedPreferences("parsedata", 0); 
     SharedPreferences.Editor editor = sendHm.edit(); 
     for (int k = 0; k < H.length; k++) { 
      editor.putString("Hm" + k, H[k]); 
     } 
     editor.commit(); 
     Intent f = new Intent(DataRetrieve.this, Calculator.class); 
     startActivity(f); 
     /* 
     * Bundle bundle = new Bundle(); bundle.putStringArray("key1", 
     * H); Intent f = new Intent(DataRetrieve.this, 
     * Calculator.class); f.putExtras(bundle); startActivity(f); 
     */ 

    } 

    catch (JSONException e) { 
     Log.e("log_tag", "Erro dados " + e.toString()); 
    } 
    } 
+0

您可能首先爲該服務器Ping服務器已關閉? –

+0

@ Hardik.Thats great.It工程!..:D。你能否解釋一下這個陳述是做什麼的?還有一件事。我現在必須把通知對話框放在else語句中。對? – renupok92

+0

TextUtils.isEmpty()檢查字符串爲空或空白,你應該把pd.dismiss()超出條件,所以我編輯我的代碼現在看到。 – Hardik

相關問題