如何修复“通过 android.view.InflateException 膨胀类片段时出错:二进制 XML 文件”

问题描述 投票:0回答:2

每当我的家庭活动在模拟器中打开时,都会显示此错误:

java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.example.adsho/com.example.adsho.HomeActivity}: 
android.view.InflateException: Binary XML file line #16 in 
com.example.adsho:layout/activity_home: Binary XML file line #22 in 
com.example.adsho:layout/content_home: Error inflating class fragment
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3622)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3786)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2257)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:233)
    at android.app.ActivityThread.main(ActivityThread.java:8030)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)
 Caused by: android.view.InflateException: Binary XML file line #16 in 
com.example.adsho:layout/activity_home: Binary XML file line #22 in 
com.example.adsho:layout/content_home: Error inflating class fragment
 Caused by: android.view.InflateException: Binary XML file line #22 in 
com.example.adsho:layout/content_home: Error inflating class fragment
 Caused by: java.lang.NullPointerException
    at com.example.adsho.ui.home.HomeFragment.onCreateView(HomeFragment.kt:58)
    at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
    at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
    at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:112)
    at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1647)
    at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3128)
    at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:3065)
    at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2988)
    at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:392)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:281)
    at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:140)
    at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
    at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:319)
    at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:298)
    at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1070)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:1131)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1092)
    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1271)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:1127)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1092)
    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:1271)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:1127)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1092)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
    at com.example.adsho.databinding.ActivityHomeBinding.inflate(ActivityHomeBinding.java:53)
2021-12-22 15:46:05.267 30467-30467/com.example.adsho E/AndroidRuntime:     at 
com.example.adsho.databinding.ActivityHomeBinding.inflate(ActivityHomeBinding.java:47)
    at com.example.adsho.HomeActivity.onCreate(HomeActivity.kt:37)
    at android.app.Activity.performCreate(Activity.java:8006)
    at android.app.Activity.performCreate(Activity.java:7990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3595)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3786)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2257)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:233)
    at android.app.ActivityThread.main(ActivityThread.java:8030)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:631)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)

我的activity_home xml文件是-

<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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    android:id="@+id/app_bar_home"
    layout="@layout/app_bar_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<com.google.android.material.navigation.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_home"
    app:menu="@menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>

这里的app_bar_home xml是-

<androidx.coordinatorlayout.widget.CoordinatorLayout
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"
tools:context=".HomeActivity">

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/Theme.Adsho.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/Theme.Adsho.PopupOverlay" />

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

<include android:id="@+id/content_home"
    layout="@layout/content_home" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

而 content_home xml 是-

<androidx.constraintlayout.widget.ConstraintLayout
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/app_bar_home">

<fragment
    android:id="@+id/nav_host_fragment_content_home"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="visible"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout> 

我从我的其他项目复制了这些 xml 文件,它们工作正常,但这里显示错误,我尝试了不同的方法,但错误没有消失。预先感谢您。

首页活动文件 -

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.google.android.material.navigation.NavigationView
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import androidx.drawerlayout.widget.DrawerLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import com.example.adsho.Model.UserInfoModel
import com.example.adsho.databinding.ActivityHomeBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*

class HomeActivity : AppCompatActivity() {

private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityHomeBinding
private lateinit var auth: FirebaseAuth
private lateinit var database: FirebaseDatabase
private lateinit var userInfoRef: DatabaseReference

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    binding = ActivityHomeBinding.inflate(layoutInflater)
    setContentView(R.layout.activity_home)

    auth = FirebaseAuth.getInstance()
    database = FirebaseDatabase.getInstance()
    userInfoRef = database.reference.child("Users")
    val currentUser = auth.currentUser

    val toolbar = binding.appBarHome.toolbar
    setSupportActionBar(toolbar)

    val drawerLayout: DrawerLayout = binding.drawerLayout
    val navView: NavigationView = binding.navView
    val navController = findNavController(R.id.nav_host_fragment_content_home)
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    appBarConfiguration = AppBarConfiguration(navController.graph, drawerLayout)
    setupActionBarWithNavController(navController, appBarConfiguration)
    navView.setupWithNavController(navController)
    navView.bringToFront()

    navView.menu.findItem(R.id.nav_sign_out).setOnMenuItemClickListener{
        signOutDialog()
        it.isCheckable = false
        true
    }

    navView.menu.findItem(R.id.nav_sign_in).setOnMenuItemClickListener {
        startActivity(Intent(this@HomeActivity, SignInActivity::class.java))
        it.isCheckable = false
        true
    }
}

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.home, menu)
    return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val id: Int = item.itemId

    if (id == R.id.action_notification_icon){
        invalidateOptionsMenu()
        findNavController(R.id.nav_host_fragment_content_home).navigate(R.id.action_notification_icon)
    }
    return super.onOptionsItemSelected(item)
}

override fun onSupportNavigateUp(): Boolean {
    val navController = findNavController(R.id.nav_host_fragment_content_home)
    return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}

// on pressing back button navigation drawer will dismiss
override fun onBackPressed() {
    if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
        binding.drawerLayout.closeDrawer(GravityCompat.START)
    }
    else {
        super.onBackPressed()
    }
}

// Sign out menu item will be shown only when user is signed in
override fun onStart() {
    super.onStart()
    val currentUser = auth.currentUser
    val signOutItem: MenuItem = binding.navView.menu.findItem(R.id.nav_sign_out)
    val signInItem: MenuItem = binding.navView.menu.findItem(R.id.nav_sign_in)
    val profileItem: MenuItem = binding.navView.menu.findItem(R.id.nav_profile)
    val navHeaderView: View = binding.navView.getHeaderView(0)
    val navHeaderUsername: TextView = navHeaderView.findViewById(R.id.nav_header_username)


    userInfoRef.child(currentUser!!.uid)
        .addListenerForSingleValueEvent(object: ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists()) {
                    val model = snapshot.getValue(UserInfoModel::class.java)
                    DBqueries.userDetailsInfo = model

                    val name: String = model!!.fullName.toString()
                    if (name.equals("anon")) {
                        navHeaderUsername.text = "Hello, anon"
                        signInItem.isVisible = true
                        signOutItem.isVisible = false
                        profileItem.isVisible = false
                    } else {
                        signOutItem.isVisible
                        signInItem.isVisible = false
                        profileItem.isVisible = true
                        navHeaderUsername.text = "Hello, $name"
                    }
                }
            }

            override fun onCancelled(error: DatabaseError) {
                Toast.makeText(this@HomeActivity, error.message, Toast.LENGTH_SHORT)
                    .show()
            }

        })
}

private fun signOutDialog() {
    val builder = AlertDialog.Builder(this@HomeActivity)
    builder.setTitle("Sign out")
        .setMessage("Do you really want to sign out?")
        .setNegativeButton("Cancel") {dialogInterface, _-> dialogInterface.dismiss()}
        .setPositiveButton("SIGN OUT") {dialogInterface, _->
            FirebaseAuth.getInstance().signOut()
            val intent = Intent(this@HomeActivity, SignInActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            startActivity(intent)
            finish()
        }.setCancelable(false)

    val dialog = builder.create()
    dialog.setOnShowListener {
        dialog.getButton(AlertDialog.BUTTON_POSITIVE)
            .setTextColor(ContextCompat.getColor(this@HomeActivity, android.R.color.holo_red_dark))
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE)
            .setTextColor(ContextCompat.getColor(this@HomeActivity, R.color.black))
    }
    dialog.show()
}

}

和主片段文件 -

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.adsho.Adapter.HomeAdapter
import com.example.adsho.DBqueries
import com.example.adsho.DBqueries.lists
import com.example.adsho.DBqueries.loadCategoriesName
import com.example.adsho.DBqueries.loadHomePage
import com.example.adsho.Model.HomeModel
import com.example.adsho.R
import com.example.adsho.databinding.FragmentHomeBinding

class HomeFragment : Fragment() {

private lateinit var homeRecyclerView: RecyclerView
private lateinit var homeRecyclerViewAdapter: HomeAdapter
private lateinit var progressBar: ProgressBar

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val root = inflater.inflate(R.layout.fragment_home, container, false)

    // jo bhi load hoga DBqueries se hoga taki speed badh sake

    progressBar = root.findViewById(R.id.home_frag_progressBar)
    val recyView: RecyclerView = root.findViewById(R.id.home_page_recyclerview)


    // Home Recycler View
    homeRecyclerView = root.findViewById(R.id.home_page_recyclerview)
    val homeLayoutManager = LinearLayoutManager(requireContext())
    homeLayoutManager.orientation = LinearLayoutManager.VERTICAL
    homeRecyclerView.layoutManager = homeLayoutManager


    // We are checking whether the list is empty or not
    // If its empty then we'll refresh the adapter
    if (lists.size == 0) {
        loadCategoriesName.add("HOME")
        lists.add(ArrayList<HomeModel>())
        homeRecyclerViewAdapter = HomeAdapter(lists[0])

        val nome: String = DBqueries.userDetailsInfo!!.fullName
        loadHomePage(homeRecyclerViewAdapter, root.context, 0, nome)


        progressBar.visibility = View.GONE
        recyView.visibility = View.VISIBLE
    } else {
        homeRecyclerViewAdapter = HomeAdapter(lists[0])
        homeRecyclerViewAdapter.notifyDataSetChanged()

        progressBar.visibility = View.GONE
        recyView.visibility = View.VISIBLE
    }
    homeRecyclerView.adapter = homeRecyclerViewAdapter

    // Home Recycler View

    return root
}

}

java android xml kotlin fragment
2个回答
1
投票

您不应该使用

DatabindingUtil.setContentView(R.layout.activity_home)
而不是
setContentView(activity, R.layout.activity_home)

如果我没记错的话就不需要打电话

binding = ActivityHomeBinding.inflate(layoutInflater)
你可以简单地

binding = DatabindingUtil.setContentView(R.layout.activity_home)

1
投票

我遇到了类似的问题,这是由于片段标签引起的。这是适合我的代码 更改自

<fragment
android:id="@+id/nav_host_fragment_content_home"
android:name="androidx.navigation.fragment.NavHostFragment"
...
app:navGraph="@navigation/mobile_navigation" />

到此

<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment_content_home"
android:name="androidx.navigation.fragment.NavHostFragment"
....
app:navGraph="@navigation/mobile_navigation" />
© www.soinside.com 2019 - 2024. All rights reserved.