在 ViewPager 抽屉布局中加载成像器时出现空指针 - 如何解决这个问题?

Null pointer on loading imager in ViewPager drawer layout - how to solve this?

我在抽屉布局(使用 NavigationView)中加载用户配置文件图像,加载发生在 MainActivity 中。该应用程序不断崩溃,并在配置文件图像的 imageView 上出现空指针错误,但如果我保持空指针检查,图像根本不会加载。图片从 Firebase 加载到 drawer_profile_image

我不知道如何解决这个问题,我尝试了多种方法但没有解决方案...无法理解此处的加载顺序。这主要发生在启动应用 post 安装时。

我在 MainActivity 上的代码

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

var drawerLayout: DrawerLayout? = null
var toggle: ActionBarDrawerToggle? = null
var navigationView: NavigationView? = null
var firstItem: TabItem? = null
var secondItem: TabItem? = null
var adapter: MainPagerAdapter? = null

var refUsers: DatabaseReference? = null
var firebaseUser: FirebaseUser? = null
private lateinit var progressBar: ProgressDialog

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val toolbar: Toolbar = findViewById(R.id.toolbar_main)
    setSupportActionBar(toolbar)
    supportActionBar!!.title = ""

    val mTabLayout: TabLayout = findViewById(R.id.tab_layout)
    val pager: ViewPager = findViewById(R.id.view_pager)

    firstItem = findViewById(R.id.firstItem)
    secondItem = findViewById(R.id.secondItem)
    

    //Drawer
    drawerLayout = findViewById(R.id.drawerLayout)
    navigationView = findViewById(R.id.nav_view)
    navigationView!!.setNavigationItemSelectedListener(this)
    toggle = ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close)
    drawerLayout!!.addDrawerListener(toggle!!)
    toggle!!.drawerArrowDrawable.color = resources.getColor(R.color.txtcolor)
    toggle!!.isDrawerIndicatorEnabled = true
    toggle!!.syncState()

    //Swipe view pager
    adapter = MainPagerAdapter(
        supportFragmentManager,
        FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,
        mTabLayout!!.tabCount
    )
    pager.adapter = adapter

    mTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab) {
            pager.currentItem = tab.position
        }

        override fun onTabUnselected(tab: TabLayout.Tab) {}
        override fun onTabReselected(tab: TabLayout.Tab) {}
    })
    pager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(mTabLayout))

    //To display fragments and to give a count of active chats
    firebaseUser = FirebaseAuth.getInstance().currentUser
    refUsers = FirebaseDatabase.getInstance().reference.child("Users").child(firebaseUser!!.uid)
    val ref = FirebaseDatabase.getInstance().reference.child("Chats")

//        //display the username and profile picture in Navigation Drawer
        refUsers!!.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(p0: DataSnapshot) {
                if (p0.exists()) {
                val user: Users? = p0.getValue(Users::class.java)
                //Store profile image in local DB

                // Display of name on the main Page toolbar removed
                    Picasso.get().load(user!!.getProfile())
                        .placeholder(R.drawable.ic_baseline_whatshot_24_white).fit().centerCrop()
                        .into(
                            findViewById<ShapeableImageView>(R.id.drawer_profile_image)
                        )
                    val firstname = user.getFirstName()
                    val surname = user.getSurName()
                    val username = "$firstname $surname"
                findViewById<TextView>(R.id.drawer_username).text = username
            }
        }

        override fun onCancelled(p0: DatabaseError) {

        }
    })

抽屉布局

<androidx.drawerlayout.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    android:theme="@style/AppTheme.Material"
    android:id="@+id/drawerLayout"
    android:background="@color/white"
    android:screenOrientation="portrait"
    tools:context=".MainActivity">

       <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >

           <com.google.android.material.appbar.AppBarLayout
               android:id="@+id/MainAppBar"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:background="@color/white"
               android:theme="@style/AppTheme.AppBarOverlay">

               <androidx.appcompat.widget.Toolbar
                   android:id="@+id/toolbar_main"
                   android:layout_width="match_parent"
                   android:layout_height="?attr/actionBarSize"
                   app:popupTheme="@style/AppTheme.PopupOverlay">

                   <TextView
                       android:id="@+id/homeTitle"
                       android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:layout_gravity="center"
                       android:text="Dashboard"
                       android:textColor="@color/txtcolor"
                       android:textSize="18sp"
                       android:textStyle="bold" />

                   <TextView
                       android:layout_width="10dp"
                       android:layout_height="10dp"
                       android:layout_gravity="end|top"
                       android:layout_marginEnd="5dp"
                       android:backgroundTint="@color/ColorRed"
                       android:background="@drawable/edittxtbg"/>

                   <ImageView
                       android:id="@+id/messages_dash"
                       android:layout_width="28dp"
                       android:layout_height="28dp"
                       android:layout_gravity="end"
                       android:src="@drawable/ic_mail" />

               </androidx.appcompat.widget.Toolbar>

           </com.google.android.material.appbar.AppBarLayout>

           <androidx.viewpager.widget.ViewPager
               android:id="@+id/view_pager"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_above="@+id/tab_layout"
               android:layout_below="@+id/MainAppBar" />

           <com.google.android.material.tabs.TabLayout
               android:id="@+id/tab_layout"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_alignParentBottom="true"
               android:layout_gravity="bottom"
               app:tabIconTint="@color/txtcolor"
               android:background="@color/white"
               app:tabIndicatorColor="@color/colorPrimaryDark"
               app:tabTextColor="@color/txtcolor">

               <com.google.android.material.tabs.TabItem
                   android:id="@+id/firstItem"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:icon="@drawable/ic_calendar_view" />

               <com.google.android.material.tabs.TabItem
                   android:id="@+id/secondItem"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:icon="@drawable/ic_person" />

           </com.google.android.material.tabs.TabLayout>
    </RelativeLayout>

    <com.google.android.material.navigation.NavigationView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/nav_view"
        app:menu="@menu/drawnavmenu"
        app:headerLayout="@layout/nav_header"
        app:itemIconTint="@color/white"
        android:background="@color/colorPrimaryDark"
        app:itemTextColor="@color/white"
        android:fitsSystemWindows="true"
        android:visibility="visible"
        android:layout_gravity="start">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:clickable="true"
            android:orientation="vertical">
            <TextView
                android:id="@+id/footer_item_1"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:gravity="center"
                android:textSize="14sp"
                android:textColor="@color/white"
                android:layout_marginBottom="15dp"
                android:text="powered by getLocal Solutions" />
        </LinearLayout>

    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

错误日志

    Process: in.trial.trial, PID: 5282
        java.lang.IllegalArgumentException: Target must not be null.
            at com.squareup.picasso.RequestCreator.into(RequestCreator.java:682)
            at com.squareup.picasso.RequestCreator.into(RequestCreator.java:665)
            at in.trial.trial.MainActivity$onCreate.onDataChange(MainActivity.kt:112)
            at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
            at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
            at com.google.firebase.database.core.view.EventRaiser.run(EventRaiser.java:55)
            at android.os.Handler.handleCallback(Handler.java:883)
            at android.os.Handler.dispatchMessage(Handler.java:100)
            at android.os.Looper.loop(Looper.java:224)
            at android.app.ActivityThread.main(ActivityThread.java:7592)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)


Left drawer menu - profile image section

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:id="@+id/navHeader"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:background="@color/white"
            android:paddingTop="30dp"
            android:paddingBottom="20dp"
            android:gravity="center">
            <com.google.android.material.imageview.ShapeableImageView
                android:id="@+id/drawer_profile_image"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:src="@drawable/ic_baseline_whatshot_24"
                app:shapeAppearanceOverlay="@style/roundedcorner"
                >
            </com.google.android.material.imageview.ShapeableImageView>
    
            <TextView
                android:layout_width="wrap_content"
                android:id="@+id/drawer_username"
                android:layout_height="wrap_content"
                android:textColor="@color/txtcolor"
                android:textSize="18sp"
                android:layout_marginTop="10dp"
                />
    
        </LinearLayout>


Nav header section - included in NavigationView


    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/navHeader"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@color/white"
    android:gravity="center"
    android:orientation="vertical"
    android:paddingTop="30dp"
    android:paddingBottom="20dp">

    <com.google.android.material.imageview.ShapeableImageView
        android:id="@+id/drawer_profile_image"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_marginTop="15dp"
        android:src="@drawable/ic_baseline_whatshot_24"
        app:shapeAppearanceOverlay="@style/roundedcorner" />

    <TextView
        android:id="@+id/drawer_username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textColor="@color/txtcolor"
        android:textSize="18sp"
        android:textStyle="bold" />

    </LinearLayout>

问题是导航视图中的 header 是从另一个布局加载的。了解到我需要先通过代码加载该视图并通过以下方式解决...在 MainActivity

中添加了以下代码
val header: View = navigationView!!.getHeaderView(0)
val drawer_profile_image = header.findViewById<ShapeableImageView>(R.id.drawer_profile_image)
val username = header.findViewById<TextView>(R.id.drawer_username)