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

Posted

技术标签:

【中文标题】Android App 在片段中创建 ListView 引用时关闭【英文标题】:Android App closes while creating a ListView Reference in a Fragment 【发布时间】:2020-07-26 08:33:56 【问题描述】:

我正在片段内创建一个自定义列表视图。 在我的主要活动中有两个选项卡。我创建了两个片段类“订阅”和“一次性”。虽然 listView 在订阅片段中被引用,但应用程序停在那里。代码构建完美,但应用程序停在那里。

片段的 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_
    android:layout_
    android:orientation="vertical"
    tools:context=".OneTime">

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

</LinearLayout>

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

    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 填充 listView,row_order

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:padding="10dp"
    android:orientation="vertical">
    <LinearLayout
        android:layout_
        android:layout_
        android:orientation="horizontal">


        <TextView
            android:id="@+id/customer_name"
            android:layout_
            android:layout_
            android:layout_weight="5"
            android:text="Customer Name"
            android:textStyle="bold">

        </TextView>

        <TextView
            android:id="@+id/address_phoneno"
            android:layout_
            android:layout_
            android:layout_weight="5"
            android:text="Phone Number"
            android:textStyle="bold">

        </TextView>

        <TextView
            android:id="@+id/amount_left"
            android:layout_
            android:layout_
            android:layout_weight="5"
            android:text="Amount Left"
            android:textStyle="bold">

        </TextView>
    </LinearLayout>

    <LinearLayout
        android:layout_
        android:layout_
        android:orientation="horizontal"
        android:paddingLeft="20sp"
        android:paddingRight="10sp">

        <TextView
            android:id="@+id/product_name"
            android:layout_
            android:layout_
            android:layout_weight="5"
            android:gravity="center_vertical"
            android:text="Product Name">

        </TextView>

        <TextView
            android:id="@+id/quantity_order"
            android:layout_
            android:layout_
            android:layout_weight="5"
            android:gravity="center_vertical"
            android:text="Qty">

        </TextView>

        <TextView
            android:id="@+id/amount_order"
            android:layout_
            android:layout_
            android:layout_weight="5"
            android:gravity="center_vertical"
            android:text="Amount">

        </TextView>

        <CheckBox
            android:id="@+id/delivered_checkbox"
            android:layout_
            android:layout_
            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 = ViewRootf4bdd0a 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 = ViewRootf4bdd0a 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)

【问题讨论】:

非常感谢您的评论。我更新了问题并按照下面的答案修复了错误。 :D 【参考方案1】:

您不能在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`

【讨论】:

以上是关于Android App 在片段中创建 ListView 引用时关闭的主要内容,如果未能解决你的问题,请参考以下文章

如何膨胀由 Android Studio 向导在 Activity 中创建的片段(列表)?

如何在片段中创建选项卡的示例?

如何隐藏默认片段 actionBar 在 android & kotlin 中创建我们自己的 actionBar

如何更改在 Google App Inventor 中创建的 android 应用程序的图标?

在 Android 中创建带有导航抽屉的汉堡菜单

在 Android Q 的外部存储中创建 App-Specific 文件夹