2014-11-22 22 views
0

嗨在這段代碼互聯網連接不檢查是否沒有互聯網意味着我的應用程序崩潰。並在這段代碼,如果我給錯誤的用戶名和密碼不調用其他condition.suppose我給錯了用戶名和密碼只是我顯示一條消息「無效的用戶名和密碼」,但該消息沒有顯示。沒有檢查的互聯網連接android

任何一個可以幫我

登錄

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

回答

0

試試這個檢查你的互聯網連接

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

上面的代碼同樣喜歡我寫 – master 2014-11-22 12:37:35

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


     } 

}

+0

嗨克里斯南我也使用相同的代碼 – master 2014-11-22 13:07:09

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; 

    } 
}