Android getActivity () returns null in Fragment

0

In an app with a side menu, when I click on one of its items, I want to load the same as clicking on another button (also in a fragment) of the application. To do this I create an object of that class and call its corresponding method from onNavigationItemSelected (), but when entering the method, it stops at:

ConnectivityManager connectivityManager = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

with the following error message:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.app.Activity.getSystemService(java.lang.String)' on a null object reference

This is how I call the method

public boolean onNavigationItemSelected(MenuItem item) {        
    int id = item.getItemId();

    if (id == R.id.miInstalaciones) {
        MainMenu_fragment mainMenu_fragment = new MainMenu_fragment();
        mainMenu_fragment.getTiposInstalacion();
    
asked by Juan 14.05.2018 в 17:47
source

1 answer

1

The problem is that you should not call a method in the instance of a Fragment that involves Actividad , without first defining the life cycle of Fragment . Your code would only work if the Fragment has been initialized, so that it already has its functional life cycle.

To be able to define the life cycle of a Fragment , you must start it with a transaction and add it to the container of the activity.

You can see an example in this Answer that I made several days ago. After you have added and initialized the Fragment correctly, you can call the method, in that example, after committing.

Another alternative is the following, similar to the Answer :

MainMenu_fragment menuFragment = new MainMenu_fragment();
Bundle arguments = new Bundle();
arguments.putBoolean("InvocarMetodo", true);
menuFragment.setArguments(arguments);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(R.id.fragment, menuFragment, "Menu");
ft.commit();

And get the value in the Fragment onCreate:

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     if(getArguments() != null && getArguments().getBoolean("InvocarMetodo", false))
        getTiposInstalacion();
}

Keep in mind that you are adding a Fragment to the container, not replacing it, just in case. If you want to summarize and pause the one already, replace it, etc ... there are other alternatives in the documentation of the transactions.

PD: If you only use the code of onNavigationItemSelected to instantiate the Fragment, then you should identify the Fragment after the commit and invoke the method after that. Since getActivity() will always arrive null if the transaction has not yet been made.

    
answered by 14.05.2018 / 20:52
source