保存与应用程序数据库CursorIndexOutOfBoundsException的联系

时间:2012-02-17 03:17:12

标签: android

在这段代码中我不断收到错误,我知道它是如何将联系人保存到数据库的。因为如果我取出cdata / cdata2并只是放一个字符串就可以了。任何帮助将不胜感激。

如何将其转换为接受来自联系人的字符串?

switch (item.getItemId()) {

    case 1:
        //Save current contact to stash database
        Cursor phones2 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null, null);
        String cdata = phones2.getString(phones2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String cdata2 = phones2.getString(phones2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        ContentValues values=new ContentValues(2);         
        values.put(DatabaseHelper.NAME, cdata);
        values.put(DatabaseHelper.cALUE, cdata2);  
        db.getWritableDatabase().insert("constants", DatabaseHelper.NAME, values);
        constantsCursor.requery();            
       //Refresh contact list
        Intent refresh = new Intent(this, MainTab.class);
        startActivity(refresh);
        this.finish();

      return(true);
      case 2:
          //uncoded option
          Toast.makeText(this, "here is the info", Toast.LENGTH_SHORT).show();
  }

错误: android.database.CursorIndexOutOfBoundsException:请求索引-1,大小为2

1 个答案:

答案 0 :(得分:2)

你忘了调用Cursor.moveToFirst(),如果没有这个调用,光标将无法从中读取。

试试这个

//Save current contact to stash database
    Cursor phones2 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null, null);
  if (phone2.moveToFirst()) {
    String cdata = phones2.getString(phone ......