我一直试图阻止在数据库为空时意外点击删除按钮。点击后它会崩溃。
数据库处理程序
public void deleteLastMessage(Class a) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_MSG + " = ?",
new String[] { String.valueOf(a.get_message()) });
db.close();
}
public String getLastString() {
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();
LastString = cursor.getString(0);
cursor.close();
db.close();
return LastString;
}
活动
public void deleteMessage(View v) {
LastMessage = new SubliminalClass(db.getLastString());
db.deleteLastMessage(LastMessage);
当有数据要删除时,它正常工作,没有数据时崩溃。 我的数据是一列字符串。 提到这个Application crashes while reading an empty table in android但无济于事。
我在下面尝试了这个,但是在没有数据时仍然崩溃了。
public boolean checkdb(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
Boolean rowExists;
String nullString="";
if (nullString.equals(getLastString())) //todo change this
// DO SOMETHING WITH CURSOR
rowExists = false;
else
{
// I AM EMPTY
rowExists = true;
}
return rowExists;
}
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:0)
试试这个
检查表row count is greater than zero
然后执行删除操作。
//添加您的活动
int rowCount = db.getRowCount();
db.close();
if(rowCount>0)
{
db.deleteLastMessage(LastMessage);
}else{
}
//在DBhelperClass中添加
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
public void deleteLastMessage(Class a) {
try{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_MSG + " = ?",
new String[] { String.valueOf(a.get_message()) });
db.close();
} catch (Exception e){
e.printStackTrace();
}
}
答案 1 :(得分:0)
您可以在删除代码周围添加try / catch。
checkdb函数也可以像这样
public boolean checkdb(){
SQLiteDatabase db = this.getReadableDatabase();
Log.d(TAG,"Got Readable DB")
Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
Boolean rowExists = false;
String nullString="";
if(mCursor != null){
Log.d(TAG,"Cursor is not null")
try{
rowExists = mCursor.getCount() > 0;
Log.d(TAG,"rowExists is " + rowExists);
mCursor.close();
} catch (Exception e){
e.printStackTrace();
}
}
return rowExists;
}