2014-05-07 79 views
-2

我決定允許progressDialog正常運行,但我故意切斷我的數據計劃(但我的WIFI和3G打開),以便應用程序認爲網絡可用,我需要用戶獲得一個消息通過Toast之後或asynctask完成運行後告訴他們存在連接困難。目前發生的事情是,當的AsyncTask完成運行時並沒有實際的互聯網服務中,progressDialog駁回和應用程序崩潰在AsyncTask期間的網絡丟失

好,我添加的代碼,讓我改一下這個問題:

我需要基本上只是通過Toast或通過Toast進行的活動,就像當您嘗試登錄您的Twitter或Facebook應用程序並且網絡不穩定或緩慢時一樣,過了一段時間對話框進度對話框消失後,您會收到一條消息網絡有一些困難。這與檢查手機上是否存在WI-FI或移動連接不同(我已經處理過)。這種情況時模擬是在連接過程中,但連接速度慢,或者不相符,或者你有沒有數據計劃認購

下面是該活動的代碼:

package com.insidetown; 

    import java.util.ArrayList; 
    import android.os.AsyncTask; 
    import java.util.HashMap; 
    import java.util.List; 
    import org.apache.http.NameValuePair; 
    import org.json.JSONArray; 
    import org.json.JSONException; 
    import org.json.JSONObject; 
    import android.app.ListActivity; 
    import android.app.ProgressDialog; 
    import android.content.DialogInterface; 
    import android.content.DialogInterface.OnDismissListener; 
    import android.content.Intent; 
    import android.os.Bundle; 
    import android.widget.ListAdapter; 
    import android.widget.ListView; 
    import android.widget.SimpleAdapter; 
    import android.widget.Spinner; 
    import android.widget.Toast; 





    public class Result extends ListActivity { 

     //final String category = ((Spinner) findViewById(R.id.spinner1)).getSelectedItem().toString(); 
     //final String location = ((Spinner) findViewById(R.id.spinner2)).getSelectedItem().toString(); 
     String category = "Flowers"; 
     String location = "Washington"; 

     // Progress Dialog 
     private ProgressDialog pDialog; 
     //private static final int LONG_DELAY = 7500; // 3.5 seconds 

     // Creating JSON Parser object 
     JSONParser jParser = new JSONParser(); 

     ArrayList<HashMap<String, String>> productsList; 

     // url to get all products list 
     private String url_all_products = "http://theURL.com.ng/123.php?category="+category+"&location="+location; 
    category="+category+"&location="+location; 

     // JSON Node names 
     private static final String TAG_SUCCESS = "success"; 
     private static final String TAG_PRODUCTS = "data"; 
     private static final String TAG_NAME = "name"; 
     private static final String TAG_ADDRESS = "address"; 
     private static final String TAG_PHONE = "phone"; 

     // products JSONArray 
     JSONArray products = null; 


     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.result); 

      // Hashmap for ListView 
      productsList = new ArrayList<HashMap<String, String>>();  

      // Loading results in Background Thread 
      new LoadAllProducts().execute(); 

      // Get listview 
      //ListView lv = getListView(); 


     } 


     /** 
     * Background Async Task to Load all product by making HTTP Request 
     * */ 
     class LoadAllProducts extends AsyncTask<String, String, String> { 

      /** 
      * Before starting background thread Show Progress Dialog 
      * */ 
      @Override 
      protected void onPreExecute() { 

       super.onPreExecute(); 
       pDialog = ProgressDialog.show(
         Result.this, 
         null, 
         "loading...", 
         true, 
         true, 
         new DialogInterface.OnCancelListener(){ 
          @Override 
          public void onCancel(DialogInterface dialog) { 
           Toast.makeText(Result.this, 
             "Operation Cancelled.", 
             Toast.LENGTH_LONG).show(); 
           // cancel the AsyncTask here! 
           LoadAllProducts.this.cancel(true); 
          } 
         } 
         ); 


       } 


      /** 
      * getting results from url 
      * */ 
      protected String doInBackground(String... args) { 
       if(pDialog != null && pDialog.isShowing()){ 
       // Building Parameters 
       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       // getting JSON string from URL 
       JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); 


       // Check your log cat for JSON reponse 
       //Log.d("Results: ", json.toString()); 


       try { 
        // Checking for SUCCESS TAG 
        int success = json.getInt(TAG_SUCCESS); 

        if (success == 1) { 
         // results returned 
         // Getting Array of results 
         products = json.getJSONArray(TAG_PRODUCTS); 

         // looping through results 
         for (int i = 0; i < products.length(); i++) { 
          JSONObject c = products.getJSONObject(i); 

          // Storing each json item in variable 

          String name = c.getString(TAG_NAME); 
          String address = c.getString(TAG_ADDRESS); 
          String phone = c.getString(TAG_PHONE); 

          // creating new HashMap 
          HashMap<String, String> map = new HashMap<String, String>(); 

          // adding each child node to HashMap key => value 

          map.put(TAG_NAME, name); 
          map.put(TAG_ADDRESS, address); 
          map.put(TAG_PHONE, phone); 

          // adding HashList to ArrayList 
          productsList.add(map); 
         } 
        }  

        else { 

         Toast.makeText(getApplicationContext(), "oops! There seems to be a problem", 3).show(); 

        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } 
       return null; 
      } 

      /** 
      * After completing background task Dismiss the progress dialog 
      * **/ 
      protected void onPostExecute(String file_url) { 

       // dismiss the dialog after getting results 
       pDialog.dismiss(); 
       // updating UI from Background Thread 
       runOnUiThread(new Runnable() { 
        public void run() { 
         /** 
         * Updating parsed JSON data into ListView 
         * */ 
         ListAdapter adapter = new SimpleAdapter(
           Result.this, productsList, 
           R.layout.list_item, new String[] { TAG_NAME, 
             TAG_ADDRESS, TAG_PHONE}, 
           new int[] { R.id.name, R.id.address, R.id.phone }); 
         // updating listview 
         setListAdapter(adapter); 
        } 
       }); 

      }  

     } 
    } 

@懶忍者和@克里斯因爲onPostExecute是主UI線程上運行

05-08 09:56:25.180: I/Choreographer(872): Skipped 65 frames! The application may be doing too much work on its main thread. 
05-08 09:56:26.470: D/dalvikvm(872): GC_FOR_ALLOC freed 35K, 3% free 3611K/3716K, paused 131ms, total 140ms 
05-08 09:56:27.530: I/Choreographer(872): Skipped 121 frames! The application may be doing too much work on its main thread. 
05-08 09:56:28.800: W/System.err(872): java.net.UnknownHostException: Unable to resolve host "insidetown.com.ng": No address associated with hostname 
05-08 09:56:28.860: W/System.err(872): at java.net.InetAddress.lookupHostByName(InetAddress.java:424) 
05-08 09:56:28.860: W/System.err(872): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 
05-08 09:56:28.860: W/System.err(872): at java.net.InetAddress.getAllByName(InetAddress.java:214) 
05-08 09:56:28.860: W/System.err(872): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 
05-08 09:56:28.860: W/System.err(872): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
05-08 09:56:28.870: W/System.err(872): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
05-08 09:56:28.870: W/System.err(872): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 
05-08 09:56:28.870: W/System.err(872): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 
05-08 09:56:28.870: W/System.err(872): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
05-08 09:56:28.890: W/System.err(872): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 
05-08 09:56:28.890: W/System.err(872): at com.insidetown.JSONParser.makeHttpRequest(JSONParser.java:67) 
05-08 09:56:28.910: W/System.err(872): at com.insidetown.Result$LoadAllProducts.doInBackground(Result.java:118) 
05-08 09:56:28.910: W/System.err(872): at com.insidetown.Result$LoadAllProducts.doInBackground(Result.java:1) 
05-08 09:56:28.910: W/System.err(872): at android.os.AsyncTask$2.call(AsyncTask.java:288) 
05-08 09:56:28.950: W/System.err(872): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
05-08 09:56:28.950: W/System.err(872): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
05-08 09:56:28.950: W/System.err(872): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
05-08 09:56:29.000: W/System.err(872): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
05-08 09:56:29.000: W/System.err(872): at java.lang.Thread.run(Thread.java:841) 
05-08 09:56:29.030: W/System.err(872): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname) 
05-08 09:56:29.040: W/System.err(872): at libcore.io.Posix.getaddrinfo(Native Method) 
05-08 09:56:29.040: W/System.err(872): at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61) 
05-08 09:56:29.040: W/System.err(872): at java.net.InetAddress.lookupHostByName(InetAddress.java:405) 
05-08 09:56:29.070: W/System.err(872): ... 18 more 
05-08 09:56:29.070: E/Buffer Error(872): Error converting result java.lang.NullPointerException: lock == null 
05-08 09:56:29.100: E/JSON Parser(872): Error parsing data org.json.JSONException: End of input at character 0 of 
05-08 09:56:29.100: W/dalvikvm(872): threadid=11: thread exiting with uncaught exception (group=0xb4a59b90) 
05-08 09:56:29.220: E/AndroidRuntime(872): FATAL EXCEPTION: AsyncTask #1 
05-08 09:56:29.220: E/AndroidRuntime(872): Process: com.insidetown, PID: 872 
05-08 09:56:29.220: E/AndroidRuntime(872): java.lang.RuntimeException: An error occured while executing doInBackground() 
05-08 09:56:29.220: E/AndroidRuntime(872): at android.os.AsyncTask$3.done(AsyncTask.java:300) 
05-08 09:56:29.220: E/AndroidRuntime(872): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 
05-08 09:56:29.220: E/AndroidRuntime(872): at java.util.concurrent.FutureTask.setException(FutureTask.java:222) 
05-08 09:56:29.220: E/AndroidRuntime(872): at java.util.concurrent.FutureTask.run(FutureTask.java:242) 
05-08 09:56:29.220: E/AndroidRuntime(872): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
05-08 09:56:29.220: E/AndroidRuntime(872): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
05-08 09:56:29.220: E/AndroidRuntime(872): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
05-08 09:56:29.220: E/AndroidRuntime(872): at java.lang.Thread.run(Thread.java:841) 
05-08 09:56:29.220: E/AndroidRuntime(872): Caused by: java.lang.NullPointerException 
05-08 09:56:29.220: E/AndroidRuntime(872): at com.insidetown.Result$LoadAllProducts.doInBackground(Result.java:127) 
05-08 09:56:29.220: E/AndroidRuntime(872): at com.insidetown.Result$LoadAllProducts.doInBackground(Result.java:1) 
05-08 09:56:29.220: E/AndroidRuntime(872): at android.os.AsyncTask$2.call(AsyncTask.java:288) 
05-08 09:56:29.220: E/AndroidRuntime(872): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
05-08 09:56:29.220: E/AndroidRuntime(872): ... 4 more 
05-08 09:56:29.260: I/Choreographer(872): Skipped 1072 frames! The application may be doing too much work on its main thread. 
05-08 09:56:30.040: I/Choreographer(872): Skipped 471 frames! The application may be doing too much work on its main thread. 
05-08 09:56:31.550: I/Choreographer(872): Skipped 606 frames! The application may be doing too much work on its main thread. 
05-08 09:56:31.680: I/Choreographer(872): Skipped 82 frames! The application may be doing too much work on its main thread. 
05-08 09:56:33.870: E/WindowManager(872): android.view.WindowLeaked: Activity com.insidetown.Result has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b4df2280 V.E..... R.....ID 0,0-304,96} that was originally added here 
05-08 09:56:33.870: E/WindowManager(872): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346) 
05-08 09:56:33.870: E/WindowManager(872): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248) 
05-08 09:56:33.870: E/WindowManager(872): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) 
05-08 09:56:33.870: E/WindowManager(872): at android.app.Dialog.show(Dialog.java:286) 
05-08 09:56:33.870: E/WindowManager(872): at android.app.ProgressDialog.show(ProgressDialog.java:116) 
05-08 09:56:33.870: E/WindowManager(872): at com.insidetown.Result$LoadAllProducts.onPreExecute(Result.java:88) 
05-08 09:56:33.870: E/WindowManager(872): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587) 
05-08 09:56:33.870: E/WindowManager(872): at android.os.AsyncTask.execute(AsyncTask.java:535) 
05-08 09:56:33.870: E/WindowManager(872): at com.insidetown.Result.onCreate(Result.java:67) 
05-08 09:56:33.870: E/WindowManager(872): at android.app.Activity.performCreate(Activity.java:5243) 
05-08 09:56:33.870: E/WindowManager(872): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
05-08 09:56:33.870: E/WindowManager(872): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140) 
05-08 09:56:33.870: E/WindowManager(872): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226) 
05-08 09:56:33.870: E/WindowManager(872): at android.app.ActivityThread.access$700(ActivityThread.java:135) 
05-08 09:56:33.870: E/WindowManager(872): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397) 
05-08 09:56:33.870: E/WindowManager(872): at android.os.Handler.dispatchMessage(Handler.java:102) 
05-08 09:56:33.870: E/WindowManager(872): at android.os.Looper.loop(Looper.java:137) 
05-08 09:56:33.870: E/WindowManager(872): at android.app.ActivityThread.main(ActivityThread.java:4998) 
05-08 09:56:33.870: E/WindowManager(872): at java.lang.reflect.Method.invokeNative(Native Method) 
05-08 09:56:33.870: E/WindowManager(872): at java.lang.reflect.Method.invoke(Method.java:515) 
05-08 09:56:33.870: E/WindowManager(872): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777) 
05-08 09:56:33.870: E/WindowManager(872): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593) 
05-08 09:56:33.870: E/WindowManager(872): at dalvik.system.NativeStart.main(Native Method) 
05-08 09:56:33.870: I/Choreographer(872): Skipped 809 frames! The application may be doing too much work on its main thread. 
05-08 09:56:34.130: I/Choreographer(872): Skipped 162 frames! The application may be doing too much work on its main thread. 
05-08 09:56:35.740: I/Process(872): Sending signal. PID: 872 SIG: 9 
+0

您應該嘗試添加最少的代碼片段來展示您遇到的問題。 – JeffS

+0

我已經添加了代碼,請看看。基本上我需要的僅僅是應用程序的響應,就像當您嘗試登錄您的Twitter或Facebook應用程序並且網絡不穩定或緩慢時一樣,過了一會兒對話框進度對話框消失並且您收到消息說網絡是有一些困難。這與檢查手機上是否存在WI-FI或移動連接不同(我已經處理過)。模擬的情況是連接速度慢或不一致,或者您沒有訂閱數據計劃 – user3591264

+0

設置一個計時器,如果網絡操作完成,則取消它。如果網絡操作不成功,計時器將觸發,您可以顯示錯誤消息並取消或忽略異步任務。 –

回答

0

您應該doInBackground使用runOnUiThread(new Runnable())()方法,而不是onPostExecute:斯特拉頓,請在下面找到墜毀的logcat的。

runOnUiThread(new Runnable() { 
      public void run() { 

       Toast.makeText(getApplicationContext(), "oops! There seems to be a problem", 3).show(); 
      } 
     }); 
+0

@懶惰忍者嗨,剛剛試過你的建議,但應用程序崩潰 – user3591264

+0

@ user3591264 - 這不是一個公平的報告。如果崩潰了,則必須提供崩潰日誌。如果合理使用這個代碼不會崩潰 - 崩潰是你的錯誤,而不是懶惰忍者的。 –

+0

@ Chris Stratton我不認爲我聽起來像是在責怪@Lazy Ninja,只是告訴他發生了什麼事情,以便他能更多地指導我。我已經發布了logcat – user3591264

0

在這裏,您可以通過添加

if (isConnectingToNetwork()) { 
     HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); 
     urlc.setRequestProperty("User-Agent", "Test"); 
     urlc.setRequestProperty("Connection", "close"); 
     urlc.setConnectTimeout(4000); 
     urlc.connect(); 
     return (urlc.getResponseCode() == 200); 
    } 

isConnectingToNetwork()檢查運行檢查是否有Wifi或移動連接,如果屬實,你會發送一個測試URL連接到谷歌和等待for reply

+0

我已經這樣做了,我在AsyncTask啓動之前檢查了Wifi或移動連接。我們所談論的情況是有無線或移動連接時,但服務器沒有響應,或者網絡速度很慢,或者過程耗時過長,或者您的互聯網訂閱中沒有數據。 – user3591264