更换自定义Data Class后出现Error inflating class fragment问题求助
Android应用切换数据类与接口后出现Fragment Inflation崩溃问题
原本使用练习提供的MarsProperty数据类和对应接口时应用运行正常,切换为自定义MarsProperty数据类并调用比利时啤酒厂数据接口后,启动时崩溃,错误为Error inflating class fragment。
错误日志
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.android.marsrealestate, PID: 26103 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.marsrealestate/com.example.android.marsrealestate.MainActivity}: android.view.InflateException: Binary XML file line #19 in com.example.android.marsrealestate:layout/activity_main: Binary XML file line #19 in com.example.android.marsrealestate:layout/activity_main: Error inflating class fragment at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4166) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4312) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101) 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:2571) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:226) at android.os.Looper.loop(Looper.java:313) at android.app.ActivityThread.main(ActivityThread.java:8741) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067) Caused by: android.view.InflateException: Binary XML file line #19 in com.example.android.marsrealestate:layout/activity_main: Binary XML file line #19 in com.example.android.marsrealestate:layout/activity_main: Error inflating class fragment Caused by: android.view.InflateException: Binary XML file line #19 in com.example.android.marsrealestate:layout/activity_main: Error inflating class fragment Caused by: java.lang.RuntimeException: Exception inflating com.example.android.marsrealestate:navigation/nav_graph line 41
相关代码
正常工作的MarsProperty数据类
@Parcelize data class MarsProperty ( val id: String, // used to map img_src from the JSON to imgSrcUrl in our class @Json(name = "img_src") val imgSrcUrl: String, val type: String, val price: Double) : Parcelable { val isRental get() = type == "rent" }
自定义的MarsProperty数据类
data class MarsProperty ( val Name: String, val imagesURL: String, val street: String, val city_name: String, val phone: String )
OverviewFragment代码
class OverviewFragment : Fragment() { private val viewModel: OverviewViewModel by lazy { ViewModelProvider(this).get(OverviewViewModel::class.java) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val binding = FragmentOverviewBinding.inflate(inflater) binding.lifecycleOwner = this binding.viewModel = viewModel binding.photosGrid.adapter = PhotoGridAdapter(PhotoGridAdapter.OnClickListener { viewModel.displayPropertyDetails(it) }) viewModel.navigateToSelectedProperty.observe(this, Observer { if ( null != it ) { // Must find the NavController from the Fragment this.findNavController().navigate(OverviewFragmentDirections.actionShowDetail(it)) // Tell the ViewModel we've made the navigate call to prevent multiple navigation viewModel.displayPropertyDetailsComplete() } }) return binding.root } }
OverviewViewModel代码
class OverviewViewModel : ViewModel() { private val _properties = MutableLiveData<List<MarsProperty>>() val properties: LiveData<List<MarsProperty>> get() = _properties private val _navigateToSelectedProperty = MutableLiveData<MarsProperty>() val navigateToSelectedProperty: LiveData<MarsProperty> get() = _navigateToSelectedProperty init { getMarsRealEstateProperties() } private fun getMarsRealEstateProperties() { viewModelScope.launch { try { _properties.value = MarsApi.retrofitService.getProperties() } catch (e: Exception) { _properties.value = ArrayList() } } } fun displayPropertyDetails(marsProperty: MarsProperty) { _navigateToSelectedProperty.value = marsProperty } fun displayPropertyDetailsComplete() { _navigateToSelectedProperty.value = null } }
activity_main.xml代码
<fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" app:navGraph="@navigation/nav_graph" />
nav_graph.xml代码
<?xml version="1.0" encoding="utf-8"?> <navigation 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/nav_graph" app:startDestination="@id/overviewFragment"> <fragment android:id="@+id/overviewFragment" android:name="com.example.android.marsrealestate.overview.OverviewFragment" android:label="fragment_overview" tools:layout="@layout/fragment_overview" > <action android:id="@+id/action_showDetail" app:destination="@id/detailFragment" /> </fragment> <fragment android:id="@+id/detailFragment" android:name="com.example.android.marsrealestate.detail.DetailFragment" android:label="fragment_detail" tools:layout="@layout/fragment_detail"> <argument android:name="selectedProperty" app:argType="com.example.android.marsrealestate.network.MarsProperty" /> </fragment> </navigation>
fragment_overview.xml代码
<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"> <data> <variable name="viewModel" type="com.example.android.marsrealestate.overview.OverviewViewModel" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.android.marsrealestate.MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/photos_grid" android:layout_width="0dp" android:layout_height="0dp" android:padding="6dp" android:clipToPadding="false" app:layoutManager="androidx.recyclerview.widget.GridLayoutManager" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:listData="@{viewModel.properties}" app:spanCount="1" tools:itemCount="16" tools:listitem="@layout/grid_view_item" /> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
问题原因及修复方案
导航参数类型不兼容
导航图中detailFragment的selectedProperty参数要求传递Parcelable类型,但自定义MarsProperty未实现该接口,导致导航图初始化验证失败,触发inflation错误。JSON字段映射缺失
自定义MarsProperty的字段名与啤酒厂接口返回的JSON字段可能不匹配,Retrofit解析会失败,间接导致Fragment初始化异常。接口数据结构适配问题
需确认新接口返回的是否为数组结构,Retrofit接口定义是否与新接口匹配。
具体修复步骤:
- 给自定义
MarsProperty添加@Parcelize注解并实现Parcelable接口,同时添加JSON字段映射注解(根据接口实际返回字段调整name值):@Parcelize data class MarsProperty ( @Json(name = "name") val Name: String, @Json(name = "images_url") val imagesURL: String, @Json(name = "street") val street: String, @Json(name = "city_name") val city_name: String, @Json(name = "phone") val phone: String ) : Parcelable - 检查
MarsApi中的getProperties()方法,确保URL和返回类型(List<MarsProperty>)适配新接口。 - 调整
PhotoGridAdapter,确保使用新MarsProperty的字段(如替换原imgSrcUrl为imagesURL),避免空指针或字段不存在问题。
内容的提问来源于stack exchange,提问作者im new no flame pls
相关产品推荐
相关产品推荐

