Выбрать контакты onClick при нажатии кнопки Android

У меня проблемы с моим приложением. То, что я хотел бы сделать, это когда моя кнопка нажата, чтобы открыть мои телефонные контакты и отобразить их в моих TextViews. У меня проблемы, когда я нажимаю кнопку, я думаю.

По крайней мере, LogCat сообщает мне об ошибке с моей кнопкой, но я не могу понять, что не так.

В моем файле манифеста я уже установил разрешения на чтение и запись контактов. У меня есть ContactView.java, где происходит код, и я уже создал представление с помощью кнопки и двух текстовых представлений.

Может быть, кто-то может мне помочь или хотя бы сказать мне, что я делаю неправильно.

На мой взгляд, я сказал: android:onClick="pickContact"

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class ContactView extends AppCompatActivity {
private static final int RESULT_PICK_CONTACT = 85500;
private TextView textView1;
private TextView textView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact_view);
    textView1 = (TextView) findViewById(R.id.TxtName);
    textView2 = (TextView) findViewById(R.id.TxtNumber);
}
public void pickContact(View v)
{
    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
    startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // check whether the result is ok
    if (resultCode == RESULT_OK) {
        // Check for the request code, we might be usign multiple startActivityForReslut
        switch (requestCode) {
            case RESULT_PICK_CONTACT:
                contactPicked(data);
                break;
        }
    } else {
        Log.e("ContactView", "Failed to pick contact");
    }
}
/**
 * Query the Uri and read contact details. Handle the picked contact data.
 * @param data
 */
private void contactPicked(Intent data) {
    Cursor cursor = null;
    try {
        String phoneNo = null ;
        String name = null;
        // getData() method will have the Content Uri of the selected contact
        Uri uri = data.getData();
        //Query the content uri
        cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        // column index of the phone number
        int  phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
        // column index of the contact name
        int  nameIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
        phoneNo = cursor.getString(phoneIndex);
        name = cursor.getString(nameIndex);
        // Set the value to the textviews
        textView1.setText(name);
        textView2.setText(phoneNo);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Вот что говорит LogCat после того, как я нажимаю кнопку addcontacts во время отладки:

    10-18 23:11:08.684    4353-4353/me.resq.resqme E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: me.resq.resqme, PID: 4353
        java.lang.IllegalStateException: Could not execute method of the activity
                at android.view.View$1.onClick(View.java:3969)
                at android.view.View.performClick(View.java:4640)
                at android.view.View$PerformClick.run(View.java:19421)
                at android.os.Handler.handleCallback(Handler.java:733)
                at android.os.Handler.dispatchMessage(Handler.java:95)
                at android.os.Looper.loop(Looper.java:136)
                at android.app.ActivityThread.main(ActivityThread.java:5476)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                at dalvik.system.NativeStart.main(Native Method)
         Caused by: java.lang.reflect.InvocationTargetException
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at android.view.View$1.onClick(View.java:3964)
                at android.view.View.performClick(View.java:4640)
                at android.view.View$PerformClick.run(View.java:19421)
                at android.os.Handler.handleCallback(Handler.java:733)
                at android.os.Handler.dispatchMessage(Handler.java:95)
                at android.os.Looper.loop(Looper.java:136)
                at android.app.ActivityThread.main(ActivityThread.java:5476)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                at dalvik.system.NativeStart.main(Native Method)
         Caused by: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:746)
                at me.resq.resqme.ContactView.pickContact(ContactView.java:28)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at android.view.View$1.onClick(View.java:3964)
                at android.view.View.performClick(View.java:4640)
                at android.view.View$PerformClick.run(View.java:19421)
                at android.os.Handler.handleCallback(Handler.java:733)
                at android.os.Handler.dispatchMessage(Handler.java:95)
                at android.os.Looper.loop(Looper.java:136)
                at android.app.ActivityThread.main(ActivityThread.java:5476)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                at dalvik.system.NativeStart.main(Native Method)

person idunnowhatimdoin    schedule 18.10.2015    source источник


Ответы (1)


private static final int RESULT_PICK_CONTACT = 85500;

Пожалуйста, попробуйте изменить его на что-то более низкое, например:

private static final int RESULT_PICK_CONTACT = 85;
person Vitaly Zinchenko    schedule 18.10.2015
comment
на самом деле сработало ... это правильный способ избавиться от этой проблемы? - person idunnowhatimdoin; 19.10.2015
comment
@idunnowhatimdoin Я не прочитал всю вашу трассировку стека, мой ответ был неправильным, поэтому я удалил его. Подробнее о том, что здесь происходит: stackoverflow.com/questions/25529865/ - person Daniel Nugent; 19.10.2015