0

I am developing an application that required to access contacts in phone. this method is executed inside a thread. But when app start for the first time it crashes and says android.permission.READ_CONTACTS or android.permission.READ_CONTACTS required as error. as soon as press on OK in on error pop up dialog box. it restart it self asking for permission and works fine.

here's the code inside fragment on onCreateView method to check whether permission already has been granted.

if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS)
                == PackageManager.PERMISSION_GRANTED) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    getContacts();
                }
            };
            Thread thread = new Thread(r);
            thread.start();
        }else{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS)) {
                    Toast.makeText(getActivity(),"Read contacts permission is required to function app correctly",Toast.LENGTH_LONG)
                            .show();
                }
                requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
            }
        }

here's the onRequestPermissionsResult method.

 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case REQUEST_READ_CONTACTS :
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        getContacts();
                    }
                };
                Thread thread = new Thread(r);
                thread.start();
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

here's the code for get contact method.

public void getContacts() {
        ContentResolver cr = getActivity().getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cur != null) {
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    String imgPath = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        Cursor ncur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
                        if (ncur != null) {
                            while (ncur.moveToNext()) {
                                String phoneNumber = ncur.getString(ncur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                String reDefinedPhoneNumber = "";
                                if (phoneNumber.contains("-")) {
                                    String[] split = phoneNumber.split("-");

                                    for (String k : split) {
                                        reDefinedPhoneNumber = reDefinedPhoneNumber.concat(k);
                                    }
                                } else if (phoneNumber.contains(" ")) {
                                    String[] split = phoneNumber.split(" ");
                                    for (String k : split) {
                                        reDefinedPhoneNumber = reDefinedPhoneNumber.concat(k);
                                    }
                                } else {
                                    reDefinedPhoneNumber = phoneNumber;
                                }
                                Contact contact = new Contact();
                                contact.setId(contact.getId());
                                contact.setName(name);
                                contact.setNumber(reDefinedPhoneNumber);
                                contact.setImgPath(imgPath);
                                contacts.add(contact);
                            }
                            ncur.close();
                        }
                    }
                }
            }
            cur.close();
        }
    }

Here's AndroidManifest.xml code.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shan.chathuranga.smsscheduler">

    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

</manifest>

what am I doing wrong. works fine in below marshmallow.

  • Gut thought - check if activity is instantiated. I have a feeling you are trying to call getActivity() before the fragment is attached to the activity, thus there isn't one. Try moving that section of code to an onAttach() overridden method. – aminner Nov 07 '16 at 15:16
  • if that the case how it works on below marshmallow ? – Chathuranga Shan Jayarathna Nov 07 '16 at 15:39
  • Because that portion of the code is never called if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) -- if you have it in the manifest prior to M will grant permission in your initial if. What's throwing the error, I'm guessing, is the Toast part. – aminner Nov 07 '16 at 15:45
  • your talking about if condition with shouldShowRequestPermissionRationale() right ? it's returns false on first time installation. it's only returns true if user revoke given permission after given that permission. I debug it. – Chathuranga Shan Jayarathna Nov 07 '16 at 15:51
  • Ok, Regardless, you're requesting permission which requires a valid activity to run. Put the following Activity activity = getActivity(); before request permission and see if it's populated. – aminner Nov 07 '16 at 16:00
  • I did it it is not the case. – Chathuranga Shan Jayarathna Nov 15 '16 at 14:49
  • Show me full error log – Volodymyr Kulyk Nov 15 '16 at 14:55
  • Here's the thing, I have a phone running cyanogenmod marshmallow. when application running on that no error message showing up. But when I tested it on sony z3 it's says permission required as error. it is my friend's phone. I don't have it with me right now. – Chathuranga Shan Jayarathna Nov 15 '16 at 15:17
  • Try this it may be help you:-http://stackoverflow.com/a/41221852/5488468 – Bipin Bharti Dec 20 '16 at 11:03

0 Answers0