导航抽屉头文本视图nullpointerexception

时间:2016-05-12 16:29:38

标签: java android nullpointerexception textview navigation-drawer

我有2个活动和服务,首先我有导航抽屉,标题中有2个文本视图,我有时必须更改文本,在服务中有一些我需要的数据 在第一次运行时,一切都很完美,但是当我从第二次进行第一次活动时,我在textviews中有nullpointerexception。是什么导致它,以及如何解决?

//First
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Navigation drawer init
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarMain);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view_main);
    navigationView.setNavigationItemSelectedListener(this);

    intent = new Intent("playbackservice");
    sConn = new ServiceConnection() {

        public void onServiceConnected(ComponentName name, IBinder binder) {
            Log.d(LOG_TAG, "MainActivity onServiceConnected");
            service = ((PlaybackService.PlaybackServiceBinder) binder).getService();
            bound = true;
            prepareLayout();
        }

        public void onServiceDisconnected(ComponentName name) {
            Log.d(LOG_TAG, "MainActivity onServiceDisconnected");
            bound = false;
        }
    };
}

private void prepareLayout() {
    Log.d(LOG_TAG, "prepareLayout: Running");
    ((TextView) findViewById(R.id.songNameNavhead)).setText(currentSong.getName());
    ((TextView) findViewById(R.id.artistNavhead)).setText(currentSong.getArtist());
}

//Layout nav_header_main.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="@dimen/nav_header_height"
          android:gravity="bottom"
          android:orientation="vertical"
          android:background="@color/colorPrimaryDark"
          android:paddingBottom="@dimen/activity_vertical_margin"
          android:paddingLeft="@dimen/activity_horizontal_margin"
          android:paddingRight="@dimen/activity_horizontal_margin"
          android:paddingTop="@dimen/activity_vertical_margin"
          android:theme="@style/ThemeOverlay.AppCompat.Dark">


<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="@string/default_song_name"
    android:id="@+id/songNameNavhead"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/default_artist"
    android:id="@+id/artistNavhead"/>
</LinearLayout>

并且

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    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"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view_main"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer"/>

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

错误

05-12 19:34:05.001 11086-11086/iskandarovlev.myitschool.ru.lyricplayer E/AndroidRuntime: FATAL EXCEPTION: main
                            Process: iskandarovlev.myitschool.ru.lyricplayer, PID: 11086
                            java.lang.NullPointerException
                            //MainActivity.java:302 is 
                            //((TextView) header.findViewById(R.id.songNameNavhead)).setText(currentSong.getName());
                            //this line
                            at iskandarovlev.myitschool.ru.lyricplayer.MainActivity.prepareLayout(MainActivity.java:302) 
                            at iskandarovlev.myitschool.ru.lyricplayer.MainActivity.access$700(MainActivity.java:48)
                            at iskandarovlev.myitschool.ru.lyricplayer.MainActivity$3.onServiceConnected(MainActivity.java:355)
                            at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1140)
                            at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1157)
                            at android.os.Handler.handleCallback(Handler.java:808)
                            at android.os.Handler.dispatchMessage(Handler.java:103)
                            at android.os.Looper.loop(Looper.java:193)
                            at android.app.ActivityThread.main(ActivityThread.java:5542)
                            at java.lang.reflect.Method.invokeNative(Native Method)
                            at java.lang.reflect.Method.invoke(Method.java:515)
                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:657)
                            at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:23)

要在Navigation Drawer的标题中成功找到任何小部件,您需要先获取标题视图。这可以通过使用getHeaderView()方法来实现:

View header = ((NavigationView)findViewById(R.id.navigation_view)).getHeaderView(0);

然后,让header指向右侧ViewGroup并使用我们的小部件,您可以像往常一样使用findViewById()

TextView tv = header.findViewById(R.id.songNameNavhead);
tv.setText(currentSong.getName());

或者以更紧凑的方式:

((TextView)header.findViewById(R.id.songNameNavhead))
                 .setText(currentSong.getName());

答案 1 :(得分:0)

private void prepareLayout() {
    Log.d(LOG_TAG, "prepareLayout: Running");
    ((TextView) findViewById(R.id.songNameNavhead)).setText(currentSong.getName());
    ((TextView) findViewById(R.id.artistNavhead)).setText(currentSong.getArtist());
}

这些需要使用navigationDrawer的视图然后是它的标题,而不是你的活动的视图,所以它应该是

View header = navigationView.getHeaderView(0)

((TextView) navigationViewHeader.findViewById(R.id.songNameNavhead)).setText(currentSong.getName());
((TextView) navigationViewHeader.findViewById(R.id.artistNavhead)).setText(currentSong.getArtist());