SQLite Cursor return NULL if no record found in Android
I have problem today about retrieving 开发者_C百科data from SQLite. Here is my coding
public Cursor fetchDictionary(String searchword) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_WORD, KEY_DEF}, KEY_WORD + "='" + searchword + "'", null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Above coding if no record found, Android prompt dialogbox and force to close. Is there any way to return "no record found" error message if no record found?
You can also do the following to check if there is data at the current column index cursor.isNull(columnIndex);
Do a try catch, and replace the e.printStackTrace()
with your messages.
You have 'throws SQLException' in your code... catch the exception and determine if the exception is due to no-record-found.
try{
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_WORD, KEY_DEF}, KEY_WORD + "='" + searchword + "'", null,
null, null, null, null);
if (mCursor != null && mCursor.getCount()>0) {
mCursor.moveToFirst();
// rest goes here
}else{
Toast.makeText(context,"No records found ",Toast.LENGTH_LONG).show();
// show error msg here
}
}catch(Exception e){
e.printStackTrace();
}
精彩评论