Java NullPointerException 与 android.support.v7.widget.Toolbar

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27810184/
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 05:05:38  来源:igfitidea点击:

NullPointerException with android.support.v7.widget.Toolbar

javaandroid

提问by hwg

I am currently trying to implement a navigation drawer in my app. I am having an issue with the Toolbar being null. I have done many searches online and tried many different solutions to no avail. I have not finished writing all the code but I can't launch my app to check the navigation drawer. Can anyone see where I went wrong?

我目前正在尝试在我的应用程序中实现导航抽屉。我遇到了工具栏为空的问题。我在网上做了很多搜索,并尝试了许多不同的解决方案,但无济于事。我还没有写完所有的代码,但我无法启动我的应用程序来检查导航抽屉。谁能看到我哪里出错了?

If there is anything else I need to post, let me know.

如果还有什么我需要发布的,请告诉我。

I included this on all my activity screens

我在我所有的活动屏幕上都包含了这个

<include
    android:id="@+id/app_bar"
    layout="@layout/app_bar"/>

app_bar.xml

app_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:minHeight="?attr/actionBarSize"
   android:background="?attr/colorPrimary"
   app:popupTheme="@style/ThemeOverlay.AppCompat.Dark" >
</android.support.v7.widget.Toolbar>

line 72 of MainActivity

MainActivity 的第 72 行

setSupportActionBar(mToolbar);

Main Activity

主要活动

public class Trans_List extends ActionBarActivity {
  private Toolbar mToolbar;
  private CharSequence mTitle;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trans_list);

        mToolbar = (Toolbar) findViewById(R.id.app_bar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.left_drawer);
        drawerFragment.setUp((DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);

Style.xml

样式文件

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppBaseTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar" >
        <item name="windowActionBar">false</item>
    </style>

    <style name="Theme.split" parent="AppBaseTheme">

    </style>

    <style name="dialog_custom" parent="@style/Theme.AppCompat.Dialog">
        <item name="@android:listPreferredItemPaddingLeft">20dip</item>
        <item name="@android:listPreferredItemPaddingRight">20dip</item>
        <item name="@android:listPreferredItemPaddingStart">20dip</item>
        <item name="@android:listPreferredItemPaddingEnd">20dip</item>
    </style>
</resources>

LogCat

日志猫

01-07 01:14:29.702    4811-4811/com.lee.yuchan.splt E/AndroidRuntime﹕
FATAL EXCEPTION: main
        Process: com.lee.yuchan.splt, PID: 4811
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lee.yuchan.splt/com.lee.yuchan.splt.Trans_List}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()'
on a null object reference
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
                at android.app.ActivityThread.access0(ActivityThread.java:144)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:135)
                at android.app.ActivityThread.main(ActivityThread.java:5221)
                at java.lang.reflect.Method.invoke(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:372)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence
android.support.v7.widget.Toolbar.getTitle()' on a null object
reference
                at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:95)
                at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:88)
                at android.support.v7.internal.app.ToolbarActionBar.<init>(ToolbarActionBar.java:84)
                at android.support.v7.app.ActionBarActivityDelegateBase.setSupportActionBar(ActionBarActivityDelegateBase.java:175)
                at android.support.v7.app.ActionBarActivity.setSupportActionBar(ActionBarActivity.java:92)
                at com.lee.yuchan.splt.Trans_List.onCreate(Trans_List.java:72)
                at android.app.Activity.performCreate(Activity.java:5933)
                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
    ????????????at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
    ????????????at android.app.ActivityThread.access0(ActivityThread.java:144)
    ????????????at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
    ????????????at android.os.Handler.dispatchMessage(Handler.java:102)
    ????????????at android.os.Looper.loop(Looper.java:135)
    ????????????at android.app.ActivityThread.main(ActivityThread.java:5221)
    ????????????at java.lang.reflect.Method.invoke(Native Method)
    ????????????at java.lang.reflect.Method.invoke(Method.java:372)
    ????????????at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    ????????????at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Main Activity XML

主要活动 XML

 <?xml version="1.0" encoding="utf-8"?>

    <android.support.v4.widget.DrawerLayout
        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:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <!-- The main content view -->
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

        <include
            layout="@layout/app_bar"/>

        <TextView
            android:id="@+id/selectItems"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/select_instr1"
            android:textSize="20sp"
            android:gravity="center"
            android:paddingTop="4sp"
            android:paddingBottom="10sp" >
        </TextView>

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="1" >
        </ListView>

        <Button
            android:id="@+id/buttonChecked"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="0dip"
            android:background="@drawable/custom_button"
            android:textColor="#ffffff"
            android:text="@string/next_button" />

    </LinearLayout>

    <!-- The navigation drawer -->
    <fragment
        android:id="@+id/left_drawer"
        android:layout_width="@dimen/nav_dr"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:layout="@layout/fragment_navigation_drawer"
        android:name="com.lee.yuchan.splt.NavigationDrawerFragment"
        tools:layout="@layout/fragment_navigation_drawer" />

    </android.support.v4.widget.DrawerLayout>

采纳答案by hwg

I solved the issue with the toolbar. I realized after hours of searching the web and trying different things, I realized that my code wasn't wrong, it was using layouts from the layout-21 not the layout folder since the emulation for Android 5.0. All modification I had made were in the layout folder. I made the changes to the xml files in the layout-21 folder and the problem was solved. Sorry for the wasted time and post.

我用工具栏解决了这个问题。经过数小时的网络搜索和尝试不同的事情后,我意识到我的代码没有错,它使用的是 layout-21 中的布局,而不是自 Android 5.0 仿真以来的布局文件夹。我所做的所有修改都在布局文件夹中。我对layout-21文件夹中的xml文件进行了修改,问题解决了。抱歉浪费了时间和帖子。

回答by Steve

Set the idattribute in the Toolbarxml like this:

idToolbarxml 中设置属性,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/app_bar"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Dark" >
</android.support.v7.widget.Toolbar>

Then remove it from the includeblock so it looks like this:

然后将其从include块中删除,使其看起来像这样:

<include
    layout="@layout/app_bar"/>

And to simplify further you could just remove the includeblock completely and simply insert the Toolbardirectly into the xml where the includewas.

为了进一步简化,您可以完全删除include块,然后将Toolbar直接插入到 xml 所在的include位置。

回答by Raissa Regis

When I had this problem, I configured the layout of the activity and of the toolbar with the same id's

当我遇到这个问题时,我用相同的 id 配置了活动和工具栏的布局

回答by Mahesh V N

<include
android:id="@+id/toolbar"
layout="@layout/tool_bar"/>

android.support.v7.widget.Toolbar.getTitle() on a null object reference happens due to title clashes between ids of and that of the id in toolbar.xml definition . To overcome this issue remove the id in as below and latest Lollipop material design shall work fine with toolbar

android.support.v7.widget.Toolbar.getTitle() 对空对象引用的发生是由于 toolbar.xml 定义中的 id 和 id 之间的标题冲突。为了解决这个问题,删除下面的 id,最新的 Lollipop 材料设计应该可以很好地与工具栏配合使用

<include
layout="@layout/tool_bar"/>

回答by Sash_KP

In my case , i was trying to access the Toolbarinside onAttach()method of a fragment instead of onActivityCreated(), resulting in NullPointerException.

就我而言,我试图访问片段的Toolbar内部onAttach()方法而不是onActivityCreated(),导致NullPointerException.

回答by Mightian

i was struck with the same issue and none of the answer's worked for me, i had actually forgotten to include the toolbar layout in the activity.

我对同样的问题感到震惊,但没有一个答案对我有用,我实际上忘记在活动中包含工具栏布局。

<include layout="@layout/toolbar"/>

回答by bkane56

Answer is a little late but I just ran into this problem.

回答有点晚了,但我刚刚遇到了这个问题。

I had a similar issue and spent 7 hrs messing with it. It worked on 3 of 4 activities just fine but one would crash.

我有一个类似的问题,并花了 7 小时搞乱它。它在 4 个活动中的 3 个上工作得很好,但一个会崩溃。

The only thing that worked for me, and I am not sure why, was to put the:

唯一对我有用的,我不知道为什么,是把:

    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true); 

as the last code in my onCreate. It works perfectly now.

作为我的 onCreate 中的最后一个代码。它现在完美地工作。

回答by Rashed Zzaman

check both line call is ok or not

检查两条线路通话是否正常

    setContentView(R.layout.layout_file)
    toolbar = (Toolbar) findViewById(R.id.toolbar_top)

回答by Cletus Ajibade

In my own case, i had used

在我自己的情况下,我用过

@Bind(R.id.toolbar)
protected Toolbar toolbar;

at the top of my code but forgot to do

在我的代码顶部但忘了做

ButterKnife.bind(this);

inside onCreate()method

内部onCreate()方法

I hope that helps someone

我希望能帮助某人

Remember to add

记得添加

 compile 'com.jakewharton:butterknife:7.0.1'

to your build.gradledependencies and import

到您的build.gradle依赖项并导入

import butterknife.Bind;
import butterknife.ButterKnife;

in your java code and rebuild your app.

在您的 Java 代码中并重建您的应用程序。

回答by nonybrighto

Another possible cause is using a wrong layout in setContentView(R.layout.yourLayout)

另一个可能的原因是在 setContentView(R.layout.yourLayout)