当将代码添加到片段活动中时,应用程序会崩溃

发布于 2025-02-04 22:05:57 字数 4191 浏览 1 评论 0原文

我是Android Studio的新手,因此我想创建一个使用导航抽屉在3个不同片段之间切换的应用程序。我使用了来自Android Studio的预制导航抽屉,我想将一些代码放入其中一个片段中。但是,一旦我初始化文本视图(或其他内容),当我尝试打开片段时,应用程序立即崩溃。

在这里,图库中的代码:

    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

有人可以告诉我我在做什么错吗? 提前致谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

归途 2025-02-11 22:05:57

您永远不会初始化testtv,因此是空的。然后,您尝试在此命令中使用它来初始化自己,这永远无法使用。

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

如果您必须使用findViewById需要在root视图上调用它,则可以从onViewCreated(例如view.find.findviewbyid()> )。但是,由于您使用的是所有不必要的绑定,因此您可以像这样直接从绑定中访问视图,

@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");
}

绑定类是一个自动生成的助手类,已经在所有上都称为findviewbyid在布局中查看并将它们保存为类成员(当您使用mybinding.inflate()呼叫创建时,它可以做到这一点。使用绑定时,您几乎不需要使用findViewById也不需要存储单个视图。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文