Home > Mobile >  App crashes when adding code into fragment activity
App crashes when adding code into fragment activity

Time:06-07

I'm new to android studio so I want to create an app that is using a navigation drawer to switch between 3 different fragments. I used the pre-built navigation drawer from android studio and I wanted to put some code into one of the fragments. But as soon as I initialize the TextView (or other things) the app immediately crashes when I try to open the fragment.

Here the code in the GalleryActivity:

    public class GalleryFragment extends Fragment {

    private FragmentGalleryBinding binding;
    private TextView testTV;


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        GalleryViewModel galleryViewModel =
                new ViewModelProvider(this).get(GalleryViewModel.class);

        binding = FragmentGalleryBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        final TextView textView = binding.textGallery;
        galleryViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
        return root;
    }


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

        testTV.setText("Hello");
    }

    public void initWidgets(){
       testTV = testTV.findViewById(R.id.text_gallery);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

fragment_gallery.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.gallery.GalleryFragment">

    <TextView
        android:id="@ id/text_gallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:textAlignment="center"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Logcat:

2022-06-07 03:32:20.006 12339-12339/com.example.testapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.testapp, PID: 12339
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.TextView.findViewById(int)' on a null object reference
        at com.example.testapp.ui.gallery.GalleryFragment.initWidgets(GalleryFragment.java:46)
        at com.example.testapp.ui.gallery.GalleryFragment.onViewCreated(GalleryFragment.java:40)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3019)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:551)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1840)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1764)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1701)
        at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:488)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2022-06-07 03:32:20.040 12339-12339/com.example.testapp I/Process: Sending signal. PID: 12339 SIG: 9

Can someone tell me what I am doing wrong? Thanks in advance!

CodePudding user response:

You never initialize testTV, so it is null. Then you try and use it to initialize itself in this command, which is never going to work.

testTV = testTV.findViewById(R.id.text_gallery); // testTV is null

If you must use findViewById you need to call it on the root view, which you could pass in from onViewCreated (e.g. view.findViewById()). However, since you are using a binding all of that is unnecessary, you can access the view directly from the binding like this

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

    // no need to save testTV as a class member, it is already
    // saved in the binding
    binding.textGallery.setText("Hello");
}

The binding class is an auto-generated helper class that has already called findViewById on all the views in the layout and saved them as class members (it does that when you create it with the MyBinding.inflate() call). When using a binding you should almost never need to use findViewById nor should you need to store off individual views.

  • Related