2012-01-03 66 views
0

我已經編寫了一個方法來檢查輸入的用戶名和密碼以及包含所有用戶名和密碼的文本文件。有趣的問題是,如果細節是正確的,那麼應用程序會繼續,但是如果細節不正確,它將返回一個NullPointerException。我的代碼如下:Java登錄方法:如果詳細信息正確則運行,但NullPointerException(如果不正確)

// Checks whether the inputed details are correct 
public boolean isCorrect(String u, String p) { 
    boolean check = false; 
    String line = null; 
    try { 
     do { 
      line = br.readLine(); 
      // System.out.println("Checking profile : " + line); 
      String[] info = line.split("\t"); 
      // nested if-statement to improve efficiency over && 
      if (info[0].equals(u)) { 
       System.out.println("username found!"); 
       if (info[1].equals(p)) { 
        System.out.println("password correct!"); 
        check = true; 
       } else System.out.println("password incorrect!"); 
      } else System.out.println("username not found!"); 
     } while (line != null && check == false); 

    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return check; 
} 

返回布爾值輸入到下面的代碼中的主要活動:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.loginpanel); 
    Button button = (Button) findViewById(R.id.btnLogin); 
      Correct = false; 



    lm = new LoginModel(this); 

    button.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      EditText textUsername = (EditText) findViewById(R.id.textUsername); 
      EditText textPassword = (EditText) findViewById(R.id.textPassword); 

      // Collect the login details entered by the user 
      String username = textUsername.getText().toString(); 
      String password = textPassword.getText().toString(); 

      // Check the application is registering the correct details 
      System.out.println(username + "\n" + password); 

      Correct = lm.isCorrect(username, password); 

      if (Correct) { // if details are correct then start main program 
       Intent intent = new Intent (LoginView.this, MenuListView.class); 
       startActivity(intent); 
      } 
      else System.out.println("Login is incorrect..."); 
     } 
    }); 
} 

什麼我不明白的是,如果正確= true,那麼它運行,爲什麼沒有問題,但如果Correct = false,它會崩潰產生FATAL EXCEPTION:main的程序,然後出現NullPointerException - 不應該只是輸出System.out.println。

+2

_不要以明文形式存儲密碼_。 **尤其是不在客戶端** – SLaks 2012-01-03 18:37:37

+1

您沒有顯示NullPointerException實際發生的位置 - 堆棧跟蹤顯示什麼? – 2012-01-03 18:38:10

+3

'//嵌套if語句以提高效率而不是錯誤。 '&&'是短路。 – SLaks 2012-01-03 18:38:22

回答

5

當你到達文件末尾時,linenull
因此,您不能在巢線(雙關意圖)中呼叫split()

但是,請勿使用此代碼。這是非常錯誤的,並且一旦發佈就會微不足道地泄露密碼。

+0

感謝指出錯誤是SLaks - 我會重寫代碼記住每個人都說過! – user1058210 2012-01-03 19:00:55

+0

而是在安全的專用服務器上使用鹽醃散列。 – SLaks 2012-01-03 19:04:42