我决定允许progressDialog正常运行,但我故意切断了我的数据计划(但我的WIFI和3G已开启),以便应用程序认为网络可用,我需要用户通过Toast获取消息在asynctask完成运行后告诉他们存在连接困难。目前发生的事情是,当asynctask完成运行并且没有实际的互联网服务时,progressDialog会解散并且应用程序崩溃
好的,我添加了代码,让我重新解释一下这个问题:
我真正需要的只是通过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);
}
});
}
}
}
@Lazy Ninja和@ Chris Stratton,请找下面崩溃的logcat:
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 :(得分:0)
你应该在doInBackground()方法上使用runOnUiThread(new Runnable() )
,而不是onPostExecute,因为onPostExecute在主UI线程上运行。
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "oops! There seems to be a problem", 3).show();
}
});
答案 1 :(得分: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或移动连接,如果为true,您将向谷歌发送测试URL连接并等待回复