Error when I Tried to show or hide a Floating Action Button from a fragment

Viewed 70

I'm trying to move from one fragment to another fragment hiding the floating action button, and then go back from the second fragment to the first fragment and show the button again. The floating action button is inside the main activity.

Mainactivity.java:

package cl.itn.cam;

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.fragment.NavHostFragment;

import android.view.View;

public class NCR extends AppCompatActivity {

    FragmentTransaction transaction;
    Fragment fragmentFirst, fragmentSecond;
    FloatingActionButton fab = findViewById(R.id.fab);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_n_c_r);

        fragmentFirst = new FirstFragment();
        fragmentSecond = new SecondFragment();


    }

    public FloatingActionButton getFloatingActionButton() {
        return fab;

    }

    public void showFloatingActionButton() {
        fab.show();
    }

    public void hideFloatingActionButton() {
        fab.hide();
    }

}

FirstFragment.java:

public class FirstFragment extends Fragment {

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


        final FloatingActionButton fab = ((NCR) getActivity()).getFloatingActionButton();

        if (fab != null) {
            ((NCR) getActivity()).hideFloatingActionButton();
        }

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                NavHostFragment.findNavController(FirstFragment.this)
                        .navigate(R.id.action_FirstFragment_to_SecondFragment);
            }
        });
    }
}

SecondFragment.java:

public class SecondFragment extends Fragment {

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


        final FloatingActionButton fab = ((NCR) getActivity()).getFloatingActionButton();

        if (fab != null) {
            ((NCR) getActivity()).showFloatingActionButton();
        }



        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_second, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_second).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(SecondFragment.this)
                        .navigate(R.id.action_SecondFragment_to_FirstFragment);
            }
        });
    }

The app crashes just when try to display the main activity with the following stack trace:

** 2021-03-19 11:04:56.979 32471-32471/cl.itn.cam E/AndroidRuntime: FATAL EXCEPTION: main Process: cl.itn.cam, PID: 32471 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{cl.itn.cam/cl.itn.cam.NCR}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3401) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3620) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2183) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:241) at android.app.ActivityThread.main(ActivityThread.java:7604) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference **

2 Answers

Try to replace

final FloatingActionButton fab = ((NCR) getActivity()).getFloatingActionButton();

with

FloatingActionButton fab = findViewById(R.id.fab);

In your Fragments. This should remove the error

Solved!

At public class NCR, I replaced "FloatingActionButton fab = findViewById(R.id.fab);" by "FloatingActionButton fab;", then on onCreate Event I added "fab = findViewById(R.id.fab);"

Thanks!

Related