2012-02-17 67 views
0

在此代码中,我不断收到错误,我知道它是如何将联系人保存到数据库。因为如果我拿出cdata/cdata2并且放一个字符串,它就可以正常工作。任何帮助将不胜感激。保存联系人到应用程序数据库CursorIndexOutOfBoundsException

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

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

回答

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 ...... 
+0

是的,但是那只是使“CDATA”串仅拉出光标的第一个位置。我需要它来匹配列表位置。 – LuisCamarena 2012-02-27 00:37:07

+0

如果你想匹配列表位置和光标,你可以调用phones2.moveToPosition(int) – iago 2012-02-28 14:49:59

相关问题