Android 在片段中创建 ListView 引用时应用关闭

Android App closes while creating a ListView Reference in a Fragment

我正在片段内创建自定义列表视图。 在我的主要 activity 中有两个选项卡。我创建了两个片段 类 "Subscribe" 和 "One Time"。虽然 listView 是 Subscribe Fragment 中的引用,但应用程序会停在那里。代码构建完美,但应用程序停在那里。

该片段的 XML 除了 ListView ID 外都是相似的。

fragment_subscibe.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".OneTime">

    <!-- TODO: Update blank fragment layout -->
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listViewSubscription">
    </ListView>

</LinearLayout>

现在在我的订阅片段 Java Class 中,我有以下方法。

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        listView = (ListView)getView().findViewById(R.id.listViewSubscription);
        Log.d("SOMETAG", "This doesn't print");
        MyAdapter adapter = new MyAdapter(getActivity().getApplicationContext(), customername, phoneNo, amountleft);
        listView.setAdapter(adapter);
       listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0) {
                    Toast.makeText(getContext(), "Position 1 Desc", Toast.LENGTH_SHORT).show();
                }
                if(position == 1) {
                    Toast.makeText(getContext(), "Position 2 Desc", Toast.LENGTH_SHORT).show();
                }
                if(position == 2) {
                    Toast.makeText(getContext(), "Position 3 Desc", Toast.LENGTH_SHORT).show();
                }
                if(position == 3) {
                    Toast.makeText(getContext(), "Position 4 Desc", Toast.LENGTH_SHORT).show();
                }


            }
        });
        return inflater.inflate(R.layout.fragment_subscribe, container, false);
    }

注释从日志标记开始的部分,创建空选项卡。 我正在使用 XML、row_order

填充 listView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">


        <TextView
            android:id="@+id/customer_name"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="5"
            android:text="Customer Name"
            android:textStyle="bold">

        </TextView>

        <TextView
            android:id="@+id/address_phoneno"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="5"
            android:text="Phone Number"
            android:textStyle="bold">

        </TextView>

        <TextView
            android:id="@+id/amount_left"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="5"
            android:text="Amount Left"
            android:textStyle="bold">

        </TextView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="20sp"
        android:paddingRight="10sp">

        <TextView
            android:id="@+id/product_name"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="5"
            android:gravity="center_vertical"
            android:text="Product Name">

        </TextView>

        <TextView
            android:id="@+id/quantity_order"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="5"
            android:gravity="center_vertical"
            android:text="Qty">

        </TextView>

        <TextView
            android:id="@+id/amount_order"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="5"
            android:gravity="center_vertical"
            android:text="Amount">

        </TextView>

        <CheckBox
            android:id="@+id/delivered_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical">

        </CheckBox>
    </LinearLayout>



</LinearLayout>

我正在关注这个视频:https://www.youtube.com/watch?v=5Tm--PHhbJo

我的错误日志如下:

2020-04-13 23:32:04.407 6602-6602/com.example.myapplication I/art:     at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:6692)
2020-04-13 23:32:04.407 6602-6602/com.example.myapplication I/art:     at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1140)
2020-04-13 23:32:04.407 6602-6602/com.example.myapplication I/art:     at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:2709)
2020-04-13 23:32:04.407 6602-6602/com.example.myapplication I/art:     at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:2825)
2020-04-13 23:32:04.407 6602-6602/com.example.myapplication I/art:     at void android.app.ActivityThread.-wrap12(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:-1)
2020-04-13 23:32:04.407 6602-6602/com.example.myapplication I/art:     at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1557)
2020-04-13 23:32:04.407 6602-6602/com.example.myapplication I/art:     at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:110)
2020-04-13 23:32:04.407 6602-6602/com.example.myapplication I/art:     at void android.os.Looper.loop() (Looper.java:203)
2020-04-13 23:32:04.407 6602-6602/com.example.myapplication I/art:     at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6339)
2020-04-13 23:32:04.408 6602-6602/com.example.myapplication I/art:     at java.lang.Object java.lang.reflect.Method.invoke!(java.lang.Object, java.lang.Object[]) (Method.java:-2)
2020-04-13 23:32:04.408 6602-6602/com.example.myapplication I/art:     at void com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run() (ZygoteInit.java:1084)
2020-04-13 23:32:04.408 6602-6602/com.example.myapplication I/art:     at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:945)
2020-04-13 23:32:04.542 6602-6602/com.example.myapplication V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = null, this = DecorView@91465fa[]
2020-04-13 23:32:04.558 6602-6602/com.example.myapplication D/WindowClient: Add to mViews: DecorView@91465fa[MainActivity], this = android.view.WindowManagerGlobal@1880975
2020-04-13 23:32:04.560 6602-6602/com.example.myapplication D/OpenGLRenderer: Dumper init 2 threads <0x9ceecd60>
2020-04-13 23:32:04.560 6602-6602/com.example.myapplication D/OpenGLRenderer: <com.example.myapplication> is running.
2020-04-13 23:32:04.563 6602-6618/com.example.myapplication D/OpenGLRenderer: CanvasContext() 0x9e747d40
2020-04-13 23:32:04.581 6602-6602/com.example.myapplication D/GraphicBuffer: register, handle(0xa54b5400) (w:576 h:960 s:576 f:0x1 u:0x000100)
2020-04-13 23:32:04.582 6602-6602/com.example.myapplication D/ViewRootImpl[MainActivity]: hardware acceleration is enabled, this = ViewRoot{f4bdd0a com.example.myapplication/com.example.myapplication.MainActivity,ident = 0}
2020-04-13 23:32:04.589 6602-6602/com.example.myapplication V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{f4bdd0a com.example.myapplication/com.example.myapplication.MainActivity,ident = 0}, this = DecorView@91465fa[MainActivity]
2020-04-13 23:32:04.616 6602-6602/com.example.myapplication D/AndroidRuntime: Shutting down VM


    --------- beginning of crash
2020-04-13 23:32:04.619 6602-6602/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 6602
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
        at com.example.myapplication.Subscribe.onCreateView(Subscribe.java:80)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
        at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManagerImpl.java:1696)
        at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:299)
        at androidx.fragment.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:259)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1244)
        at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
        at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
        at android.view.View.measure(View.java:20234)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6249)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1705)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:797)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
        at android.view.View.measure(View.java:20234)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6249)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:214)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:20234)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6249)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1705)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:797)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
        at android.view.View.measure(View.java:20234)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6249)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:214)
        at android.view.View.measure(View.java:20234)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6249)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1705)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:797)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:657)
        at android.view.View.measure(View.java:20234)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6249)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:214)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:716)
        at android.view.View.measure(View.java:20234)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2655)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1596)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1869)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1481)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7047)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:910)
        at android.view.Choreographer.doCallbacks(Choreographer.java:712)
        at android.view.Choreographer.doFrame(Choreographer.java:646)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:896)
        at android.os.Handler.handleCallback(Handler.java:836)
2020-04-13 23:32:04.619 6602-6602/com.example.myapplication E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:103)
        at android.os.Looper.loop(Looper.java:203)
        at android.app.ActivityThread.main(ActivityThread.java:6339)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1084)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:945)

您不能在 createView 中调用 getView 因为您正在创建视图(尚未创建以获取它)替换 createView 中的这一行:

listView = (ListView)getView().findViewById(R.id.listViewSubscription);

这些行:

View rootView = inflater.inflate(R.layout.fragment_subscribe, container, false);
listView = (ListView) rootView.findViewById(R.id.listViewSubscription);
// other codes...
return rootView// return from `createView`