通过row_Id SQLite检索特定行的列值的异常

时间:2011-10-24 12:29:46

标签: android sqlite

我创建了一个包含四列的数据库。

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE contacts (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT, type TEXT);");
  }

现在我有一个特定行的_id,我正在尝试检索该特定行的列值(四列值)。我的代码如下。

 public Cursor getById(String id) {

    String[] args = { id };
    return (getReadableDatabase().rawQuery("SELECT _id, name, email, type FROM contacts WHERE _id=?", args));
 }

 Cursor c = getById(row_id);
 String name = c.getString(1);

它的以下例外情况。

Uncaught handler: thread main exiting due to uncaught exception
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
at com.app.friendlist.FriendList$2.onItemClick(FriendList.java:109)
at android.widget.AdapterView.performItemClick(AdapterView.java:284)
at android.widget.ListView.performItemClick(ListView.java:3285)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:1640)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4363)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
at dalvik.system.NativeStart.main(Native Method)

请帮助并提出问题所在。感谢。

1 个答案:

答案 0 :(得分:3)

您需要像这样使用它 -

 Cursor c = getById(row_id);
 if(c.getCount()>0)
 {
     c.moveToFirst();
     String name = c.getString(1);
 }