1

如果我的设备没有连接到互联网,那么它应该在 Toast 中给出互联网连接错误。但是我的应用程序崩溃了。它不会捕获 No Internet Connection 的错误。我的代码在互联网连接上完美运行。请帮我

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
4

4 回答 4

2

我认为,您有 Window Leak,因为当没有 Internet 连接时,您的代码正在访问 doInBackground 方法中的 UI 线程。在您的 ReadContent 方法中查看您的 Toast 消息。如果没有互联网并且出现异常,您的 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;
    }

然后,当您启动 AsyncTask 时,请这样做

if(isOnline()){
   // Start your AsyncTask
} else{
  // Show internet not available alert
}

您还需要添加 ACCESS_NETWORK_STATE 权限才能使用此方法。希望能帮助到你。

于 2013-10-17T15:02:57.443 回答
0

问题是您在Toast.makeTextdoInBackground. 这个方法是接触UI线程,里面是禁止的doInBackground,你应该根据你的查询结果调用Toast.makeTextfrom 。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之前检查 Internet 连接,并且只处理 AsyncTask 代码中的 IO 错误等。Ayon 的解决方案将为此工作。

于 2013-10-17T15:09:46.577 回答
0

你必须把你的祝酒词放在主 ui 线程中,如下所示:

runOnUiThread(new Runnable() {
    public void run() {
        // runs on UI thread
          Toast.makeText(getBaseContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();

    }
});

把两个都像这样,你的问题就解决了!;)

于 2013-10-17T15:10:35.847 回答
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();

希望这会帮助你。

于 2013-10-17T15:22:56.517 回答