Android 应用程序崩溃,而不是给出Internet连接错误

Android 应用程序崩溃,而不是给出Internet连接错误,android,Android,如果我的设备未连接到internet,则应在Toast中显示internet连接错误。但是我的应用程序崩溃了。它不会捕获没有Internet连接的错误。我的代码在internet连接上工作得很好。请帮帮我 private class MyAsyncTask extends AsyncTask<String, Integer, String>{ @Override protected String doInBackground(String... p

如果我的设备未连接到internet,则应在Toast中显示internet连接错误。但是我的应用程序崩溃了。它不会捕获没有Internet连接的错误。我的代码在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;
    }
私有类MyAsyncTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…参数){
//TODO自动生成的方法存根
字符串s=postData();
返回s;
}
受保护的void onPostExecute(字符串结果){
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG.show();
}
受保护的void onProgressUpdate(整数…进度){
pb.setProgress(progress[0]);
}
公共字符串postData(){
//创建一个新的HttpClient和Post头
字符串OrigResponsetText=“”;
试一试{
DefaultHttpClient httpclient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://localhost/ServletParams/AndroidServlet");
//添加您的数据cnic、mobileNo、姓名、地址、nextkin
List nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“param1”,cnic));
添加(新的BasicNameValuePair(“param2”,mobileNo));
添加(新的BasicNameValuePair(“参数3”,名称));
添加(新的BasicNameValuePair(“参数4”,地址));
添加(新的BasicNameValuePair(“param5”,nextkin));
添加(新的BasicNameValuePair(“param6”,sendImages));
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
/*执行*/
HttpResponse response=httpclient.execute(httppost);
HttpEntity rp=response.getEntity();
OrigResponsetText=readContent(响应);
} 
捕获(客户端协议例外e){
//TODO自动生成的捕捉块
Toast.makeText(getBaseContext(),“无Internet连接”,Toast.LENGTH_SHORT.show();
} 
捕获(IOE异常){
//TODO自动生成的捕捉块
Toast.makeText(getBaseContext(),“对不起”,Toast.LENGTH_SHORT.show();
}
字符串responseText=origresponseText.substring(7,origresponseText.length());
返回响应文本;
}
}
字符串读取内容(HttpResponse响应)
{
字符串文本=”;
InputStream in=null;
试一试{
in=response.getEntity().getContent();
BufferedReader reader=新的BufferedReader(新的InputStreamReader(in));
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
某人附加(行);
}
text=sb.toString();
}捕获(非法状态){
Toast.makeText(getBaseContext(),“对不起”,Toast.LENGTH_SHORT.show();
}捕获(IOE异常){
Toast.makeText(getBaseContext(),“对不起”,Toast.LENGTH_SHORT.show();
}
最后{
试一试{
in.close();
}捕获(例外情况除外){
Toast.makeText(getBaseContext(),“对不起”,Toast.LENGTH_SHORT.show();
}
}
返回文本;
}
这是一份日志:

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
10-17 19:45:05.061:E/AndroidRuntime(22597):原因:java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序
10-17 19:45:05.061:E/AndroidRuntime(22597):在android.os.Handler.(Handler.java:121)
10-17 19:45:05.061:E/AndroidRuntime(22597):在android.widget.Toast$TN.(Toast.java:322)
10-17 19:45:05.061:E/AndroidRuntime(22597):在android.widget.Toast(Toast.java:91)
10-17 19:45:05.061:E/AndroidRuntime(22597):在android.widget.Toast.makeText(Toast.java:238)上
10-17 19:45:05.061:E/AndroidRuntime(22597):在com.example.androidufoneapp.CustomerRegistration0$MyAsyncTask.postData(CustomerRegistration0.java:647)
10-17 19:45:05.061:E/AndroidRuntime(22597):在com.example.androidufoneapp.CustomerRegistration0$MyAsyncTask.doInBackground(CustomerRegistration0.java:602)
10-17 19:45:05.061:E/AndroidRuntime(22597):在com.example.androidufoneapp.CustomerRegistration0$MyAsyncTask.doInBackground(CustomerRegistration0.java:1)
10-17 19:45:05.061:E/AndroidRuntime(22597):在android.os.AsyncTask$2.call(AsyncTask.java:287)
10-17 19:45:05.061:E/AndroidRuntime(22597):位于java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-17 19:45:05.061:E/AndroidRuntime(22597):。。。4更多

我认为,您有窗口泄漏,因为当没有internet连接时,您的代码正在使用doInBackground方法访问UI线程。在ReadContent方法中查看Toast消息。如果没有internet,您的Toast消息将访问UI线程,并且出现异常。但由于您的应用程序当时处于后台线程中,因此您将出现窗口泄漏错误,并且应用程序将崩溃,因为您无法从后台线程访问应用程序UI

确定..要解决此问题,请从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;
    }
然后当你开始你的异步任务时,像这样做

if(isOnline()){
   // Start your AsyncTask
} else{
  // Show internet not available alert
}
if (AppUtility.determineConnectivity(this))
  new MyAsyncTask().execute();
else
Toast.makeText(this, "sorry! No Internet Connection", Toast.LENGTH_SHORT).show();

要使用此方法,还需要添加访问\网络\状态权限。希望能有所帮助。

问题在于您正在调用
Toast.makeText
方法,该方法由
doInBackground
调用。此方法正在接触UI线程,这在
doInBackground
中是禁止的,您应该调用
Toast。
runOnUiThread(new Runnable() {
    public void run() {
        // runs on UI thread
          Toast.makeText(getBaseContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();

    }
});
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();