我正在开发应用程序,其中第一个活动从数据库中获取随机值,并将其作为字符串发送到下一个活动。
我确切知道如何在sql中完成:
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
在尝试在应用程序中使用它之后,我来到了这个:
Cursor send = database.query(TABLE_NAME, new String[] { COLUMN_NAME }, null, null, null, null, "RANDOM() LIMIT 1");
Bundle b = new Bundle();
b.putString("description", send.getString(send.getColumnIndex(COLUMN_NAME)));
但按下按钮打开第二个活动后,我在最后一行收到错误。
添加了日志:
05-22 22:14:24.202: E/AndroidRuntime(14259): FATAL EXCEPTION: main
05-22 22:14:24.202: E/AndroidRuntime(14259): android.database.CursorIndexOutOfBoundsException: Index 1 requested, with a size of 1
05-22 22:14:24.202: E/AndroidRuntime(14259): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:400)
05-22 22:14:24.202: E/AndroidRuntime(14259): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
05-22 22:14:24.202: E/AndroidRuntime(14259): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
05-22 22:14:24.202: E/AndroidRuntime(14259): at com.example.ListAction$1.onItemClick(ListAction.java:90)
05-22 22:14:24.202: E/AndroidRuntime(14259): at android.widget.AdapterView.performItemClick(AdapterView.java:292)
05-22 22:14:24.202: E/AndroidRuntime(14259): at android.widget.AbsListView.performItemClick(AbsListView.java:1177)
05-22 22:14:24.202: E/AndroidRuntime(14259): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2705)
05-22 22:14:24.202: E/AndroidRuntime(14259): at android.widget.AbsListView$1.run(AbsListView.java:3458)
05-22 22:14:24.202: E/AndroidRuntime(14259): at android.os.Handler.handleCallback(Handler.java:605)
05-22 22:14:24.202: E/AndroidRuntime(14259): at android.os.Handler.dispatchMessage(Handler.java:92)
05-22 22:14:24.202: E/AndroidRuntime(14259): at android.os.Looper.loop(Looper.java:137)
05-22 22:14:24.202: E/AndroidRuntime(14259): at android.app.ActivityThread.main(ActivityThread.java:4507)
05-22 22:14:24.202: E/AndroidRuntime(14259): at java.lang.reflect.Method.invokeNative(Native Method)
05-22 22:14:24.202: E/AndroidRuntime(14259): at java.lang.reflect.Method.invoke(Method.java:511)
05-22 22:14:24.202: E/AndroidRuntime(14259): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
05-22 22:14:24.202: E/AndroidRuntime(14259): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
05-22 22:14:24.202: E/AndroidRuntime(14259): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:2)
我认为问题是您应该将光标指向第一行。我在你的代码中找不到这个:
if (!send.moveToFirst()) {
Log.d(TAG, "Cannot move to first row of the Cursor!");
return;
}
答案 1 :(得分:1)
改为使用rawQuery
:
database.rawQuery("SELECT column
FROM table
ORDER BY RANDOM() LIMIT 1",null);
您将获得相同类型的cursor
,但正如您在sql中通常所做的那样执行查询。
所以假设你的第二部分代码是正确的:
Cursor send =database.rawQuery("SELECT column
FROM table
ORDER BY RANDOM() LIMIT 1",null);
Bundle b = new Bundle();
b.putString("description", send.getString(send.getColumnIndex(COLUMN_NAME)));