Ants
Ants

Reputation: 390

How to get Android getActivity within Fragment

I decided to start my project using the "bottomNavigation Activity" template that Android studio provides. the java folder structure is as follows:

com.example.project 
    + ui (package)
    +     - dashboard (package)
    +        - DashboardFragment (java)
    +        - DashoardViewModel (java)
    + MainActivity (java)

I have a textview within the fragment_dashboard.xml, I use it to display the region where the user is from. But in order to use "ContextCompat.checkSelfPermission(...)" and "ActivityCompat.requestPermissions(...)" I need to supply "this" but because it is a fragment then I need to supply "getContext" and "getActivity". It's always null.

How do I get "getActivity" and "getContext"?

Here is part of my code:

public class DashboardFragment extends Fragment {

private DashboardViewModel dashboardViewModel;
private static final int REQUEST_CODE_LOCATION_PERMISSION = 1;
private TextView txtLocation;
private ResultReceiver resultReceiver;
private Activity activity = getActivity();

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {

    dashboardViewModel = ViewModelProviders.of(this).get(DashboardViewModel.class);
    root = inflater.inflate(R.layout.fragment_dashboard, container, false);
    //final TextView textView = root.findViewById(R.id.text_dashboard);
    dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            //      textView.setText(s);
        }
    });

    //Get user location
    resultReceiver = new AddressResultReceiver(new Handler());
    txtLocation = root.findViewById(R.id.txt_dashboard_user_loc);
    if(activity != null) {

        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                   activity,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_CODE_LOCATION_PERMISSION);
        } else {
            getCurrentLocation();
        }//if-else
    }//if
    else{
        Log.e("HELLO","null");
    }

    return root;
}//onCreateView

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == REQUEST_CODE_LOCATION_PERMISSION && grantResults.length > 0) {
        getCurrentLocation();
    } else {
        Toast.makeText(getContext(), "Permission denied!", Toast.LENGTH_LONG).show();
    }//if-else
}

}//DashboardFragment

I used a tutorial but they wrote their code in main_activity.

Please help!

Tony

Upvotes: 0

Views: 2114

Answers (2)

OhhhThatVarun
OhhhThatVarun

Reputation: 4321

It's null because you are assigning it before it even instantiated.

public class DashboardFragment extends Fragment {

    private DashboardViewModel dashboardViewModel;
    private static final int REQUEST_CODE_LOCATION_PERMISSION = 1;
    private TextView txtLocation;
    private ResultReceiver resultReceiver;
   // private Activity activity = getActivity(); <-- Didn't instantiated yet that's why it's null
    private Activity activity;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        dashboardViewModel = ViewModelProviders.of(this).get(DashboardViewModel.class);
        return inflater.inflate(R.layout.fragment_dashboard, container, false);
    } //onCreateView

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        activity = getActivity();
        // Put all the code here. Don't put unnecessary code in onCreateView
        //final TextView textView = view.findViewById(R.id.text_dashboard);
        dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer < String > () {
            @Override
            public void onChanged(@Nullable String s) {
                //      textView.setText(s);
            }
        });

        //Get user location
        resultReceiver = new AddressResultReceiver(new Handler());
        txtLocation = root.findViewById(R.id.txt_dashboard_user_loc);
        if (activity != null) {

            if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                    activity,
                    new String[] {
                        Manifest.permission.ACCESS_FINE_LOCATION
                    },
                    REQUEST_CODE_LOCATION_PERMISSION);
            } else {
                getCurrentLocation();
            } //if-else
        } //if
        else {
            Log.e("HELLO", "null");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE_LOCATION_PERMISSION && grantResults.length > 0) {
            getCurrentLocation();
        } else {
            Toast.makeText(getContext(), "Permission denied!", Toast.LENGTH_LONG).show();
        } //if-else
    }

Upvotes: 1

Ara Mkrtchyan
Ara Mkrtchyan

Reputation: 507

Override the onAttach method, it provides a context. Keep a global parameter of type context and assign it to context in onattach

Upvotes: 0

Related Questions