2012-05-04 43 views
3

由於某些原因,當我找不到輸入的用戶名時,應用程序崩潰。但是,當用戶名被發現時,它似乎運行完美。我甚至做了檢查,看看返回的遊標== null。繼承人的代碼Android SQLite CursorIndexOutOfBounds

public boolean isUserAuthenticated(String username, String password) { 
    // TODO Auto-generated method stub 
    boolean authenticated = false; 
    String[] columns = new String[] {LOGIN_USERNAME, LOGIN_PASSWORD}; 
    String sqlUsername = "\"" + username + "\""; 
    Cursor c = ourDatabase.query(LOGIN_TABLE, columns, LOGIN_USERNAME + "="+ sqlUsername, null, null, null, null); 
    if (c != null) { 
     c.moveToFirst(); 
     String passwordAttachedToUsername = c.getString(1); 
     if(passwordAttachedToUsername.equals(password)) { 
      authenticated = true; 
     } 
    } 

    return authenticated; 
} 

回答

3

光標對象可能不爲空,但其結果集的大小爲0而不是:

if (c != null) { 
    ... 
} 

嘗試:

if (c.getCount() > 0) { 
    ... 
} 

而且, @mu太短,你可以在你的條件中使用c.moveToFirst()的返回值:

if (c.moveToFirst()) { 
    String passwordAttachedToUsername = c.getString(1); 
    if (passwordAttachedToUsername.equals(password)) { 
     authenticated = true; 
    } 
} 
+2

或者你可以檢查'moveToFirst'返回值將返回true:HTTP:/ /developer.android.com/reference/android/database/Cursor.html#moveToFirst%28%29 –

+0

是的。這比我的解決方案更清潔。 – anon

0

query命令將始終返回一個遊標,以便您對null的測試將始終失敗。您需要檢查計數指針包含使用cursor.getCount()

+0

難道你不是這個意思:你對null的測試總是會通過? –

2

首先,條件應該是:

if (c != null && c.getCount() > 0) 

其次,你可以重構

String passwordAttachedToUsername = c.getString(1); 
if(passwordAttachedToUsername.equals(password)) { 
    authenticated = true; 
    } 

與此相反:

authenticated = password.equals(c.getString(1)); 
1

更改:

if (c != null) { 
    c.moveToFirst(); 
    ... 
} 

if (c != null && c.moveToFirst()) { 
    ... 
} 

如果c != null和光標的大小大於0

0
if (cursor != null && cursor.getCount() > 0) { 
if (c.moveToFirst()) { 
      String passwordAttachedToUsername = c.getString(1); 
      if(passwordAttachedToUsername.equals(password)) { 
      authenticated = true; 
    }} 
        // your logic goes here 
       } else { 
        Toast.makeText(getApplicationContext(), "No Record Found", 1000).show(); 
       }