Reputation: 153
I tried to use Contextcompat
and ActivityCompat
in Fragment but it shows
error "Error:(49, 50) error: incompatible types: CallFragment cannot be converted to Context" and "Error:(51, 51) error: incompatible types: CallFragment cannot be converted to Activity".
if(ContextCompat.checkSelfPermission(this,Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL);
}
How can I solve this?
Upvotes: 0
Views: 1904
Reputation: 3
Though it's late, but I hope someone finds this helpful.
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS}, 101);
}
Upvotes: 0
Reputation: 364
private Context context;
public Yourclassname(Context context) {
this.context = context;
}
use context instead of "this" and use this below code
if(ContextCompat.checkSelfPermission(context,android.Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context, new String[]{android.Manifest.permission.CALL_PHONE}, REQUEST_CALL);
}
Upvotes: 1
Reputation: 18222
We this clearly means that you need Context
and Activity
reference. Since you are using the code inside a Fragment class this
<-- refers to the Fragment and not to Activity
or Context
.
How to get Context reference?
get it in the onAttachMethod(Context context)
method available in Fragment class.
class YourFragment extends Fragment{
private Context context;
@Override
public void onAttach(Context context)
{
this.context = context;
}
}
How to get Activity reference in Fragment?
getActivity();
or
(Activity)context;
Upvotes: 0
Reputation: 411
if(ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL); }
use getContext() instead of this in the fragment
Upvotes: 1