Home > Software engineering >  How to use public method in fragment
How to use public method in fragment

Time:03-29

i am making a call blocker. I'm trying to run a code that works in an mainActivity in a fragment.

    @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_READ_PHONE_STATE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getActivity(), "Permission granted"  PERMISSION_REQUEST_READ_PHONE_STATE , Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(getActivity(), "Permission NOT granted: "   PERMISSION_REQUEST_READ_PHONE_STATE, Toast.LENGTH_SHORT).show();
            }

            return;
        }
    }
}

onCreateView=

   @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_call, container, false);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        if (getActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED || getActivity().checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_DENIED) {
            String[] permissions = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE};
            requestPermissions(permissions, PERMISSION_REQUEST_READ_PHONE_STATE);
        }
    }

    onRequestPermissionsResult();

    return view;
}

the problem is public void onRequestPermissionsResult There is a line above it, when I hover over it, "onRequestPermissionsResult" shows this message. I tried several methods and ways, I hope someone can help me solve it.

CodePudding user response:

Is that Activity hosting your Fragment? If that's the case, you can use getActivity() in your Fragment and cast it to MainActivity.

((MainActivity)getActivity()).onRequestPermissionsResult();

However, if that's not the case, please provide more details, as you should not try to access any activities to which your fragment's not related.

  • Related