互联网连接没有检查android

时间:2014-11-22 11:51:52

标签: android

嗨在此代码中Internet连接不检查是否没有互联网意味着我的应用程序崩溃了。在此代码中,如果我提供错误的用户名和密码而不是调用else condition.suppose我给了错误的用户名和密码我就是显示一条消息"无效的用户名和密码"但那条消息没有显示出来。

任何人都可以帮助我

登录

public class Login extends Activity {
    ImageButton login;
    private static final Pattern USERNAME_PATTERN = Pattern
            .compile("[a-zA-Z0-9]{1,250}");
    private static final Pattern PASSWORD_PATTERN = Pattern
            .compile("[a-zA-Z0-9+_.]{4,16}");
    EditText usname,pword,ustype;
    TextView tv;
    Boolean isInternetPresent = false;
    String username1,password;
    HttpPost httppost;
    StringBuffer buffer;
    String queryString;
    String data="";
    int i;
    HttpResponse response;
    HttpClient httpclient;
    CheckBox mCbShowPwd;
    String[] username,user_type;

    ProgressDialog dialog = null;
     ConnectionDetector cd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login);

        login = (ImageButton)findViewById(R.id.login);  
        usname = (EditText)findViewById(R.id.username);
        pword= (EditText)findViewById(R.id.password);
        ustype= (EditText)findViewById(R.id.usertype);
        tv = (TextView)findViewById(R.id.tv);
        mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
        cd = new ConnectionDetector(getApplicationContext());
       mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (!isChecked) {

                    pword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {

                     pword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
            }
        });

       login.setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View v) {

               new Thread(new Runnable() {
                    public void run() {

               isInternetPresent = cd.isConnectingToInternet();
               if (isInternetPresent) {



               } else {

                   showAlertDialog(Login.this, "No Internet Connection",
                           "You don't have internet connection.", false);
               }

                    }
               }).start();


               String username1 = usname.getText().toString();
               String password = pword.getText().toString();

               queryString = "username=" + username1 + "&password="
                        + password ;
               String user_type1 = DatabaseUtility.executeQueryPhp("usertype",queryString);
               System.out.print(user_type1);

               try
               {
                JSONArray JA = new JSONArray(user_type1);



                username = new String[JA.length()];
                user_type = new String[JA.length()];




                for(int i=0;i<JA.length();i++)
                {
                    username[i] = JA.getJSONObject(i).getString("username");
                    user_type[i] = JA.getJSONObject(i).getString("user_type");

                }




               }
               catch(Exception e)
               {
                   Log.e("Fail 3", e.toString());
                   e.printStackTrace();
               }
               if (username1.equals("") || password.equals("")) {
                   if (username1.equals("")) {
                       Toast.makeText(Login.this, "ENTER USERNAME",
                               Toast.LENGTH_LONG).show();

                   }
                   if (password.equals("")) {
                       Toast.makeText(Login.this, "ENTER PASSWORD",
                               Toast.LENGTH_LONG).show();

                   }

               } else if (!CheckUsername(username1) && !CheckPassword(password)){
                       Toast.makeText(Login.this, "ENTER VALID USERNAME & PASSWORD",
                             Toast.LENGTH_LONG).show();
               }
               else{
                  final String usertype =user_type[i].toString();
                   try{
                   queryString = "username=" + username1 + "&password="
                    + password +"&user_type="+usertype;
                   final String data = DatabaseUtility.executeQueryPhp("login",queryString);

            System.out.println("data ::"+data.length());
            runOnUiThread(new Runnable() {
                public void run() {


                }
            });

            if(data.equalsIgnoreCase("Admin user Found")){
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(Login.this,"Login Success", Toast.LENGTH_SHORT).show();

                    }
                });

                startActivity(new Intent(Login.this, Home.class));
            }
            else if(data.equalsIgnoreCase("Student User Found")){
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(Login.this,"Login Success", Toast.LENGTH_SHORT).show();
                        usname.setText("");
                           pword.setText("");
                    }
                });


                Intent i = new Intent(Login.this, Student_Attendance.class);

                i.putExtra("username",username1);
            startActivity(i);



            }

            else if(data.equalsIgnoreCase("Teacher  user Found")){
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(Login.this,"Login Success", Toast.LENGTH_SHORT).show();

                    }
                });

                startActivity(new Intent(Login.this, Home.class));
            }
            else {
                tv.setText("InValid UserName and Password");

            }
         tv.setText("");
            }catch(Exception e){
                dialog.dismiss();

                System.out.println("Exception : " + e.getMessage());
            }
               }
               usname.setText("");
               pword.setText("");      


            }
         });

    }



            private boolean CheckPassword(String password) {

                return PASSWORD_PATTERN.matcher(password).matches();
            }

            private boolean CheckUsername(String username) {

                return USERNAME_PATTERN.matcher(username).matches();
            }
            public void showAlertDialog(Context context, String title, String message, Boolean status) {
                AlertDialog alertDialog = new AlertDialog.Builder(context).create();

                // Setting Dialog Title
                alertDialog.setTitle(title);

                // Setting Dialog Message
                alertDialog.setMessage(message);

                // Setting alert dialog icon
                alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

                // Setting OK Button
                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });

                // Showing Alert Message
                alertDialog.show();
            }
    }

ConnectionDetector

public ConnectionDetector(Context context){
    this._context = context;
}
public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
      }
      }

3 个答案:

答案 0 :(得分:0)

尝试此操作以检查您的互联网连接

ConnectivityManager connectivityManager
            = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    isInternetPresent = activeNetworkInfo != null && activeNetworkInfo.isConnected();

答案 1 :(得分:0)

试试这个

public class ConnectionDetector {

private Context _context;

public ConnectionDetector(Context context){
    this._context = context;
}
public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager)    
  context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
      }
      }

这里是示例注册活动

       public class RegisterActivity extends Activity {

       AlertDialogManager alert = new AlertDialogManager();
       ConnectionDetector cd;
       EditText txtName;
       EditText txtEmail;
       Button btnRegister;
       @Override
       public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_register);
        cd = new ConnectionDetector(getApplicationContext());
        if (!cd.isConnectingToInternet())
       {
        alert.showAlertDialog(RegisterActivity.this,
                "Internet Connection Error",
                "Please connect to working Internet connection", false);
        return;
       }
      if (SERVER_URL == null || SENDER_ID == null || SERVER_URL.length() == 0
            || SENDER_ID.length() == 0) {
        alert.showAlertDialog(RegisterActivity.this, "Configuration Error!",
                "Please set your Server URL and GCM Sender ID", false);
         return;
    }   
    txtName = (EditText) findViewById(R.id.txtName);
    txtEmail = (EditText) findViewById(R.id.txtEmail);
    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            String name = txtName.getText().toString();
            String email = txtEmail.getText().toString();
            if(name.trim().length() > 0 && email.trim().length() > 0){
                // Launch Main Activity
                Intent i = new Intent(getApplicationContext(), GCMMainActivity.class);
                i.putExtra("name", name);
                i.putExtra("email", email);
                startActivity(i);
                finish();
            }else{

                alert.showAlertDialog(RegisterActivity.this, "Registration Error!",  
                "Please enter your details", false);
            }
        }
        });


         }

}

答案 2 :(得分:0)

//USing This Class You can check InternetConnection
--------------------------------------------------------


public class IntennetConnection {
    public static boolean CheckNetConnectivity(Context mContext) {
        ConnectivityManager connec = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
                || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED)
            return true;

        return false;

    }
}