Android 检查游标是否有结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10108385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if cursor has results
提问by Faas
I am using a database to store date and want a single column returned based on which id is given in the where claus.
我正在使用数据库来存储日期,并希望根据 where 子句中给出的 id 返回单个列。
public String getPmax(String serial) {
String[] columns = new String[]{KEY_SERIAL, KEY_PMAX};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, "serial = " + serial,
null, null, null, null);
String result = "nothing found";
if(c != null) {
int iPmax = c.getColumnIndex(KEY_PMAX);
c.moveToFirst();
result = c.getString(iPmax);
}
return result;
}
This code works if I use a serial that is in the database but it gives me a force close when i am using a serial that's not in the database!
如果我使用数据库中的序列号,则此代码有效,但是当我使用不在数据库中的序列号时,它会强制关闭!
it says:
它说:
04-11 16:31:19.423: E/AndroidRuntime(21226): java.lang.RuntimeException: Unable to start activity ComponentInfo{nl.janjanus.solardetect/nl.janjanus.solardetect.DatabaseView}: android.database.sqlite.SQLiteException: no such column: g: , while compiling: SELECT serial, pmax FROM SolareCel WHERE serial = g
So my question is: How do I check if there is result? or do I need to check if the serial given is a serial that is in the database?
所以我的问题是:我如何检查是否有结果?还是我需要检查给定的序列号是否是数据库中的序列号?
回答by Samir Mangroliya
if (!(mCursor.moveToFirst()) || mCursor.getCount() ==0){
//cursor is empty
}
回答by j0ntech
If you look closely, the error is that the SQL is faulty.
It reads the g
as a column. You have to encase it in apostrophes like so 'g'
.
如果仔细观察,错误是 SQL 有问题。它将 读g
作一列。你必须像这样用撇号包裹它'g'
。
In your case, the line where you get the cursor should be:
在您的情况下,您获得光标的行应该是:
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, "serial = '" + serial + "'",
null, null, null, null);
As to checking whether the cursor has no results, look at Samir Mangroliya's answer.
至于检查光标是否没有结果,看Samir Mangroliya的回答。
回答by DGomez
You can check if the Cursor has elements:
您可以检查 Cursor 是否有元素:
boolean isEmpty = cursor.getCount() < 1;
AFAIK, the Cursor never returns null when there is no row which the requested conditions, just return a empty Cursor.
AFAIK,当没有请求条件的行时,Cursor 永远不会返回 null,只返回一个空的 Cursor。
回答by Joe
int x = cursor.getCount(); //this will return number of records in current cursor
if ( x == 0 ) {
// there are no records
} else {
// do your stuff
}