0

I am trying to access Contacts from Emulator simply on API 23 but can't check permission at run time. Here is Code

I added in Manifest

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

content_main`

   <ListView
    android:id="@+id/contact_names"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="16dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:layout_marginTop="16dp"
    android:scrollbars="vertical"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    />

contact_detail.xml`

<TextView
    android:id="@+id/name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView"
    tools:text="TextView"/>

MainActivity.java

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";
private ListView contactNames;
private static final int REQUEST_CODE_READ_CONTACTS = 1;
private static boolean READ_CONTACTS_GRANTED = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    contactNames = (ListView) findViewById(R.id.contact_names);
    int hasReadContactPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
    Log.d(TAG, "onCreate: checkSelfPermission "+ hasReadContactPermission);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d(TAG, "fab onClick: starts");
            String[] projection={ContactsContract.Contacts.DISPLAY_NAME_PRIMARY};
            ContentResolver contentResolver = getContentResolver();
            Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,
                    projection,
                    null,
                    null,
                    ContactsContract.Contacts.DISPLAY_NAME_PRIMARY);

            if(cursor!=null){
                List<String> contacts=new ArrayList<String>();
                while (cursor.moveToNext()){
                    contacts.add(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
                }
                cursor.close();
                ArrayAdapter<String> adapter=new ArrayAdapter<String>(MainActivity.this,R.layout.contact_detail,R.id.name,contacts);
                contactNames.setAdapter(adapter);
            }
            Log.d(TAG, "fab onClick: ends");
        }
    });
    Log.d(TAG, "onCreate: ends");
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Log.d(TAG, "onRequestPermissionsResult: starts");
    switch (requestCode){
        case REQUEST_CODE_READ_CONTACTS:{
            //if request canclled then ResultArray is Empty
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //permission granted,do the contacts related task you need to do
                Log.d(TAG, "onRequestPermissionsResult: permission granted");
                READ_CONTACTS_GRANTED = true;
            }else {
                //permission denied
                //disabled the functionalities that depends on this permission
                Log.d(TAG, "onRequestPermissionsResult: permission refused");
            }
        }
    }
    Log.d(TAG, "onRequestPermissionsResult: ends");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.o`enter code here`nOptionsItemSelected(item);
}

}

whenever I clicked on floating action Button App crashed.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Denish Rana
  • 101
  • 2
  • 11

3 Answers3

0

if you don't have permission it returns false then request permission

ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_CONTACTS},
                    1);

then it will show popup window.

Ganesh Gudghe
  • 1,327
  • 1
  • 17
  • 41
0

You need to first request permission using the below example code inside your onClick -

    if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] {Manifest.permission.WRITE_CONTACTS},
                REQUEST_CODE_ASK_PERMISSIONS);
        return;
    }
    insertDummyContact();

You can learn more about it from here

hsm59
  • 1,991
  • 19
  • 25
0

Make two methods, and on click of your fab check the Version(place this call inside your onClickListener)

if(Build.VERSION.SDK_INT >= 21){
//check for permission
    if(!checkPermissionForContact()){
    //raise permission dialog
    requestPersmissionForContacts();
    return;
    }
}

two methods are:

public boolean checkPermissionForContact(){
    int result = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS);
    if(result == PackageManager.PERMISSION_GRANTED){
        return true;
    }else{
        return false;
    }
}

 public void requestPersmissionForContacts(){
    if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.READ_CONTACTS)){
        Toast.makeText(MainActivity.this, "Contact Reading Permission needed. Please allow in App Settings for addition functionality.",Toast.LENGTH_LONG).show();
    }else {
        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_CONTACTS}, CONTACTS_PERMISSION_REQUEST_CODE);
    }
}
Ashwani
  • 1,294
  • 1
  • 11
  • 24