如果我的设备未连接到互联网,那么它应该在Toast中提供互联网连接错误。但我的应用程序崩溃了。它没有捕获无Internet连接错误。我的代码完全适用于互联网连接。请帮帮我
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String s=postData();
return s;
}
protected void onPostExecute(String result){
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
public String postData() {
// Create a new HttpClient and Post Header
String origresponseText="";
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/ServletParams/AndroidServlet");
// Add your data cnic,mobileNo,name,address,nextkin
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("param1",cnic));
nameValuePairs.add(new BasicNameValuePair("param2", mobileNo));
nameValuePairs.add(new BasicNameValuePair("param3", name));
nameValuePairs.add(new BasicNameValuePair("param4", address));
nameValuePairs.add(new BasicNameValuePair("param5", nextkin));
nameValuePairs.add(new BasicNameValuePair("param6", sendImages));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* execute */
HttpResponse response = httpclient.execute(httppost);
HttpEntity rp = response.getEntity();
origresponseText=readContent(response);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(), "sorry", Toast.LENGTH_SHORT).show();
}
String responseText = origresponseText.substring(7, origresponseText.length());
return responseText;
}
}
String readContent(HttpResponse response)
{
String text = "";
InputStream in =null;
try {
in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
text = sb.toString();
} catch (IllegalStateException e) {
Toast.makeText(getBaseContext(), "sorry", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Sorry", Toast.LENGTH_SHORT).show();
}
finally {
try {
in.close();
} catch (Exception ex) {
Toast.makeText(getBaseContext(), "Sorry", Toast.LENGTH_SHORT).show();
}
}
return text;
}
这是一个日志:
10-17 19:45:05.061: E/AndroidRuntime(22597): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
10-17 19:45:05.061: E/AndroidRuntime(22597): at android.os.Handler.<init>(Handler.java:121)
10-17 19:45:05.061: E/AndroidRuntime(22597): at android.widget.Toast$TN.<init>(Toast.java:322)
10-17 19:45:05.061: E/AndroidRuntime(22597): at android.widget.Toast.<init>(Toast.java:91)
10-17 19:45:05.061: E/AndroidRuntime(22597): at android.widget.Toast.makeText(Toast.java:238)
10-17 19:45:05.061: E/AndroidRuntime(22597): at com.example.androidufoneapp.CustomerRegistrationL0$MyAsyncTask.postData(CustomerRegistrationL0.java:647)
10-17 19:45:05.061: E/AndroidRuntime(22597): at com.example.androidufoneapp.CustomerRegistrationL0$MyAsyncTask.doInBackground(CustomerRegistrationL0.java:602)
10-17 19:45:05.061: E/AndroidRuntime(22597): at com.example.androidufoneapp.CustomerRegistrationL0$MyAsyncTask.doInBackground(CustomerRegistrationL0.java:1)
10-17 19:45:05.061: E/AndroidRuntime(22597): at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-17 19:45:05.061: E/AndroidRuntime(22597): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-17 19:45:05.061: E/AndroidRuntime(22597): ... 4 more
答案 0 :(得分:2)
我认为,你有Window Leak,因为当没有互联网连接时,你的代码正在访问doInBackground方法中的UI线程。在ReadContent方法中查看Toast消息。你的Toast消息将访问UI线程,如果没有互联网并且它有异常。但是当你的应用程序在后台线程当时,所以你会得到窗口泄漏错误,应用程序将崩溃,因为你无法访问App UI背景线程。
Ok ..要修复此问题,请从PostData方法中删除Toast消息。如果要显示toast,则在onPostExecute方法中显示它。我建议另一个好方法。
使用此方法使用以下方法检查连接是否可用
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
}
return false;
}
然后当您启动AsyncTask时,请执行此操作
if(isOnline()){
// Start your AsyncTask
} else{
// Show internet not available alert
}
您还需要添加ACCESS_NETWORK_STATE权限才能使用此方法。希望它有所帮助。
答案 1 :(得分:0)
问题是您在Toast.makeText
调用的方法中调用doInBackground
。此方法触及在doInBackground
内禁止的UI线程,您应根据查询结果从Toast.makeText
调用onPostExecute
。
你可以这样做:
protected void onPostExecute(String result){
if (!result.equals("")){ // Check to see if String result contains a result or in case or error, is still your empty String you assigned it
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_LONG).show();
// errorMessage can be a String that you keep track of inside your catch clauses or a generic error message
}
}
您还需要从Toast.makeText
方法中的catch子句中删除对readContent
的所有来电。
此外,最好在启动AsyncTask之前检查之前的网络连接,并且只处理AsyncTask代码中的IO错误等。 Ayon的解决方案将适用于此。
答案 2 :(得分:0)
你必须把你的祝酒词放在主ui线程中,如下所示:
runOnUiThread(new Runnable() {
public void run() {
// runs on UI thread
Toast.makeText(getBaseContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
});
将两者都放在这样,你的问题就会解决! ;)
答案 3 :(得分:0)
在调用AsyncTask之前,首先检查连接。
创建一个名为AppUtility的类。
public class AppUtility {
/**
* Determine connectivity. a utility method to determine Internet
* connectivity this is invoked before every web request
*
* @param ctx
* the context
* @return true, if successful
*/
public static boolean determineConnectivity(Context context) {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
return info != null && info.getState() == NetworkInfo.State.CONNECTED;
}
}
并检查这样的连接
if (AppUtility.determineConnectivity(this))
new MyAsyncTask().execute();
else
Toast.makeText(this, "sorry! No Internet Connection", Toast.LENGTH_SHORT).show();
希望这会对你有所帮助。