Java 空指针异常:名称 == 空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18082495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:16:57  来源:igfitidea点击:

NullPointerException: name == null

javaandroidandroid-layoutandroid-fragmentsnullpointerexception

提问by MikkoP

I'm developing an Android application that uses Fragments. I got this error.

我正在开发一个使用 Fragments 的 Android 应用程序。我收到了这个错误。

Caused by: java.lang.NullPointerException: name == null

What does name == nullmean? Here's the full log

什么name == null意思?这是完整的日志

08-04 15:02:22.422: E/AndroidRuntime(2499): FATAL EXCEPTION: main
08-04 15:02:22.422: E/AndroidRuntime(2499): java.lang.RuntimeException: Unable to start activity ComponentInfo{fi.peltoset.mikko.home/fi.peltoset.mikko.home.Koti}: android.view.InflateException: Binary XML file line #17: Error inflating class fragment
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.ActivityThread.access0(ActivityThread.java:130)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.os.Looper.loop(Looper.java:137)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.ActivityThread.main(ActivityThread.java:4745)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at java.lang.reflect.Method.invokeNative(Native Method)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at java.lang.reflect.Method.invoke(Method.java:511)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at dalvik.system.NativeStart.main(Native Method)
08-04 15:02:22.422: E/AndroidRuntime(2499): Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class fragment
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:256)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.Activity.setContentView(Activity.java:1867)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at fi.peltoset.mikko.home.Koti.onCreate(Koti.java:13)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.Activity.performCreate(Activity.java:5008)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
08-04 15:02:22.422: E/AndroidRuntime(2499):     ... 11 more
08-04 15:02:22.422: E/AndroidRuntime(2499): Caused by: java.lang.NullPointerException: name == null
08-04 15:02:22.422: E/AndroidRuntime(2499):     at java.lang.VMClassLoader.findLoadedClass(Native Method)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:354)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at java.lang.ClassLoader.loadClass(ClassLoader.java:491)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.Fragment.instantiate(Fragment.java:574)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.Fragment.instantiate(Fragment.java:552)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.app.Activity.onCreateView(Activity.java:4656)
08-04 15:02:22.422: E/AndroidRuntime(2499):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
08-04 15:02:22.422: E/AndroidRuntime(2499):     ... 21 more

This is in a class called Navigation. It extends android.app.Fragment.

这是在一个名为Navigation. 它延伸android.app.Fragment

In it's onCreateViewmethod I inflate the layout and return it. In the onActivityCreatedmethod I check if the layout has two panes (I have different layouts for different devices) and based on that I add onClickListeners to these.

在它的onCreateView方法中,我膨胀了布局并返回它。在该onActivityCreated方法中,我检查布局是否有两个窗格(我对不同的设备有不同的布局),并基于此向这些窗格添加 onClickListeners。

My code looks like this.

我的代码看起来像这样。

public class Navigation extends Fragment {
    private OnItemSelectedListener listener;
    private boolean dualPane = false;

    public interface OnItemSelectedListener {
        public void onMenuItemSelected(int fragmentId);
    }

    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if(activity instanceof OnItemSelectedListener) {
            this.listener = (OnItemSelectedListener) activity;
        } else {
            ...
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_navigation, container, false);

        return view;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        View contentPane = getActivity().findViewById(R.id.contentFragment);
        dualPane = contentPane != null && contentPane.getVisibility() == View.VISIBLE;

        if(dualPane) {
            final ListView menu = (ListView) getActivity().findViewById(R.id.valikko);

            menu.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

            String[] texts = new String[] {
                    ...
            };

            ArrayList<MenuItem> items = new ArrayList<MenuItem>();
            items.add(new MenuItem("Home", R.drawable.koti2));
            ...

            ImageArrayAdapter adapter = new ImageArrayAdapter(getActivity(), items, texts);
            menu.setAdapter(adapter);

            menu.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String item = ((TextView) view.findViewById(R.id.label)).getText().toString();

                    listener.onMenuItemSelected(0); // TODO ...
                }           
            });
        } else {
            ImageView btnYleiskatsaus   = (ImageView) getActivity().findViewById(R.id.btnYleiskatsaus);
            ...

            btnYleiskatsaus.setOnClickListener(onMenuClikkedListener);
            ...
        }       
    }

    private OnClickListener onMenuClikkedListener = new OnClickListener() {

        @Override
        public void onClick(View v) {           
            ...         
        }
    };
}

The layout file layout-sw720dp-land/activity_navigation.xmllooks this

布局文件layout-sw720dp-land/activity_navigation.xml看起来像这样

<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:background="@color/pressed_koti"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/valikko"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </ListView>
</LinearLayout>

Here is the activity_koti.xmlfile.

这是activity_koti.xml文件。

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

    <fragment 
        android:id="@+id/menuFragment"
        android:layout_width="300dp"
        android:layout_height="match_parent"
        class="fi.peltoset.mikko.home.Navigation" />

    <fragment 
        android:id="@+id/contentFragment"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" />
</LinearLayout>

I ran the application on an emulator with Android 4.1.2.

我在带有 Android 4.1.2 的模拟器上运行了该应用程序。

What causes these errors and how do I fix them?

导致这些错误的原因是什么,我该如何解决?

回答by Robadob

You should use android:nameto point to your fragments instead of class, it is also necessary to include the same attribute for your second fragment, this would explain the name==null.

您应该使用android:name指向您的片段而不是class,还需要为您的第二个片段包含相同的属性,这将解释name==null.

Edit:Apparently class may be interchangeable with android:name, but I would follow what the docs use.

编辑:显然 class 可以与 android:name 互换,但我会遵循文档使用的内容。

It should be;

它应该是;

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

    <fragment 
        android:id="@+id/menuFragment"
        android:layout_width="300dp"
        android:layout_height="match_parent"
        android:name="fi.peltoset.mikko.home.Navigation" />

    <fragment 
        android:id="@+id/contentFragment"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:name="I NEED A NAME" />
</LinearLayout>

http://developer.android.com/training/basics/fragments/creating.html#AddInLayout

http://developer.android.com/training/basics/fragments/creating.html#AddInLayout

回答by Geobits

When you add a fragment in the XML file, you need to give it a nameattribute. That's why it says "name = null", because you're not doing that.

在 XML 文件中添加片段时,需要为其赋予一个name属性。这就是为什么它说“name = null”,因为你没有这样做。

See the guide for adding Fragmentsfor more.

有关更多信息,请参阅添加 Fragments 的指南

回答by Mena

Try adding a classto your second fragment in activity_koti.xmlif you're referencing it in your FragmentActivity.

尝试添加class到您的第二个片段中activity_koti.xml,如果你在你引用它FragmentActivity

Or, as Robadob says, add android:name:"your.path.YourName"to both.

或者,正如 Robadob 所说,将android:name:"your.path.YourName"两者相加。

Interesting additional info on classvs android:namein XML references to Fragments here.

在有趣的附加信息classVSandroid:name在XML中引用Fragment小号这里