2012-02-17 66 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

相關問題