简体   繁体   English

我的Android应用需要通过点击按钮来验证与互联网的连接,但是应用使用我的代码时却崩溃了

[英]My Android app needs to verify connection to internet onClick of a button but app is crashing on using my code

I need to verify the internet connection while pressing log-out button in my app and it must show a toast message "connection error" if connection is not present and must not go to the login page. 我需要在按我的应用程序中的注销按钮时验证互联网连接,如果不存在连接,则它必须显示一条吐司消息“连接错误”,并且不能转到登录页面。

Following is the error code that i had received in the console window while running the emulator. 以下是运行模拟器时在控制台窗口中收到的错误代码。

Android Runtime Errors: Fatal Exception: thread -85 Android运行时错误:致命异常:线程-85

java.lang.RuntimeException: Can't create handler inside thread. java.lang.RuntimeException:无法在线程内创建处理程序。

I had created a class called "appstatus.java" and used it and working fine with the login page but while i try to use same if else condition with the "mainactivity.java" where logout button is present. 我创建了一个名为“ appstatus.java”的类,并使用了它,并且可以在登录页面上正常工作,但是当我尝试使用存在“退出”按钮的“ mainactivity.java”条件时,我尝试使用相同的类。 its not working and app crashes. 它无法正常工作,应用崩溃。 below is my code:- 下面是我的代码:

@Override public void onClick(View v) { @Override public void onClick(View v){

new Thread(new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub

        if (AppStatus.getInstance(getBaseContext()).isOnline(getBaseContext())) {
            //




        Log.v("driver-id from logout:",""+drv_id);  


        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost(ServerConnection.ip+"LogoutFlag.jsp");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        Log.v("drv id from logout:",""+drv_id);
        nameValuePairs.add(new BasicNameValuePair("driver_id", ""+drv_id));



    try {


        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = httpclient.execute(httppost, responseHandler);
        String reverseString = response.trim();
        Log.v("Response device id from logout",reverseString);




    }
     catch (Exception e) {


        Log.e("logout error:",e.toString());

     }
            }
        else {
         Toast.makeText(getBaseContext(), "Connection Lost", Toast.LENGTH_SHORT).show();
        }
    }
}).start();

I had used same if, else condition to check internet connectivity on the login page and is working fine. 我曾经使用过相同的if,else条件来检查登录页面上的互联网连接,并且工作正常。 here the only difference i notice is a try catch method is used. 在这里,我注意到的唯一区别是使用了try catch方法。

My question is:- 我的问题是:

  1. Why the app is crashing with above code? 为什么应用程序崩溃并显示上述代码?

  2. How to rewrite the code avoiding errors for the above mentioned cause? 如何重写代码以避免上述原因的错误?

Any piece of code is highly appreciated and thanks in advance. 任何代码都将受到高度赞赏,并在此先感谢。

Try this way,hope this will help you to solve your problem 尝试这种方式,希望这将帮助您解决问题

Follow few steps to check internet connection and make code without crashes 遵循几个步骤来检查互联网连接,并使代码不崩溃

Step 1. make this method, for checking connection is available or not 步骤1.制作此方法,以检查连接是否可用

  void isConnectedToInternet() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni != null)
        greenFlag();
    else
        new AlertDialog.Builder(activity)
                .setTitle("Network connection error !")
                .setMessage("Please check internet settings to continue.")
                .setNegativeButton("Continue",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                isConnectedToInternet();
                            }
                        }).show();

}

Step 2. Run this method on oncreate, 步骤2.在oncreate上运行此方法,

         isConnectedToInternet();

Step 3. In this mehtod you need to put all data related to webservices and others task, 第3步。在此方法中,您需要放入与Web服务和其他任务相关的所有数据,

      void greenFlag() {

    // Anything you want to do here 
        }

thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM