我是android的新手。我有一个允许用户编辑联系人的应用程序。在那个应用程序中,我有我联系,问题是当我尝试编辑它时,通过检索我的联系人,它总是在logcat中显示错误。我使用以下代码,但它无法正常工作。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor cursor = getApplicationContext().getContentResolver().query(uri, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
long idContact = cursor.getLong(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
Intent i = new Intent(Intent.ACTION_EDIT);
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, idContact);
i.setData(contactUri);
i.putExtra("finishActivityOnSaveCompleted", true);
startActivity(i);
}
});
}
Logcat是.....
01-31 15:06:48.396 13800-13800/com.example.admin.editaction E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.editaction, PID: 13800
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 12
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:74)
at android.database.CursorWrapper.getLong(CursorWrapper.java:127)
at com.example.admin.editaction.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
答案 0 :(得分:2)
在阅读数据时不要忘记移动Cursor
:
while (cursor.moveToNext()) {
long idContact = cursor.getLong(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
}
或者,如果假设只有一个条目,
if (cursor.moveToFirst()) {
long idContact = cursor.getLong(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
}