Android: lazy-loading of DataBinding view throws exception - android
There is a large data-bound view, which may take several seconds to inflate. I would like to display the user a splash screen and inflate the main view a delayed action. Android studio throws an exception "Failed to call observer method".
MainActivity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.screen_splash)
Handler(Looper.getMainLooper()).postDelayed({
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(
this,
R.layout.activity_main
)
binding.lifecycleOwner = this // this line throws exception
}, 1000)
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:bind="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="vm"
type="com.example.ViewModel"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/map_list"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
</RelativeLayout>
Exception:
2021-12-05 13:42:56.638 23701-23701/com.example E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example, PID: 23701
java.lang.RuntimeException: Failed to call observer method
at androidx.lifecycle.ClassesInfoCache$MethodReference.invokeCallback(ClassesInfoCache.java:226)
at androidx.lifecycle.ClassesInfoCache$CallbackInfo.invokeMethodsForEvent(ClassesInfoCache.java:194)
at androidx.lifecycle.ClassesInfoCache$CallbackInfo.invokeCallbacks(ClassesInfoCache.java:185)
at androidx.lifecycle.ReflectiveGenericLifecycleObserver.onStateChanged(ReflectiveGenericLifecycleObserver.java:37)
at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:354)
at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:196)
at androidx.databinding.ViewDataBinding.setLifecycleOwner(ViewDataBinding.java:434)
at com.example.databinding.ActivityMainBindingImpl.setLifecycleOwner(ActivityMainBindingImpl.java:166)
at com.example.MainActivity.onCreate$lambda-3(MainActivity.kt:106)
at com.example.MainActivity.$r8$lambda$lffeScwTEbHi2B1isKEoQYU2po4(Unknown Source:0)
at com.example.MainActivity$$ExternalSyntheticLambda5.run(Unknown Source:2)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
Caused by: java.lang.NumberFormatException: s == null
at java.lang.Integer.parseInt(Integer.java:577)
at java.lang.Integer.valueOf(Integer.java:801)
at com.example.databinding.ControlPanelBindingImpl.executeBindings(ControlPanelBindingImpl.java:800)...
I am not sure about the structure of your application. In our case we had a similar requirement where we wanted to show a loader until the initial fragment is bound. So we created a viewStub in the activity. Then when the fragment is attached we set a liveData in the shared view model to SHOW which notifies the activity to inflate the viewStub. This way we inflate the view stub which hides the full screen displaying a splash image. Then once the view in the fragment is created and in the onViewCreated we again set the liveData in the shared view model to HIDE which hides the viewStub and the fragment is displayed.
Use fragmentContainerView inside your main activity. Show the view that you want to show in this container. Create a view in front of the container. Show splash message in this view. Make the visibility of the splash view gone when the main view is loaded. So the splash screen will use the activity life cycle and the main view will use the fragment lifecycle. This may be a solution for you.
Disclaimer: turns out that the issue is resolved in UPDATE 2 section
in the answer; the other sections are left if they could help future visitors in other potential issues
At first look, thought that Caused by: java.lang.NumberFormatException: s == null is related to the issue; although you told in comments that it's working synchronously.
And the exception java.lang.RuntimeException: Failed to call observer method won't help to know the error by tracing it in the code.
But your code successfully worked with me in simple layouts; probably the issue is related to the heavy layout that you try to load synchronously along while accessing the binding.lifecycleOwner; I guess the latter snippet requires a while before accessing the lifecycleOwner. So, you could post some delay in advance.
For that, I am going to use coroutines instead of posting a delay; as the code would be more linear and readable:
CoroutineScope(Main).launch {
delay(1000) // Original delay of yours
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(
this#MainActivity,
R.layout.activity_main
)
delay(1000) // try and error to manipulate this delay
binding.lifecycleOwner = this#MainActivity
}
If not already used, the coroutine dependency is
def coroutine_version = "1.5.2"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutine_version"
UPDATE
The posted delay in your code doesn't help in showing the splash/launch screen during that delay while the main activity is loading;
Handler(Looper.getMainLooper()).postDelayed({
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(
this,
R.layout.activity_main
) // This won't be called unless the 1000 sec is over
binding.lifecycleOwner = this
}, 1000)
What your code does:
A splash screen is shown
A delay is posted (still the main layout is not loading in here)
main layout is shown when the delay is over
So, the posted delay is just accumulating to the time of loading the main layout; this even make it more lagged. Furthermore this is not the recommended way of using splash screen (This medium post would help in that)
Instead, I think what you intend to do:
Show a splash screen
Load main layout
Post a delay so that the main layout takes time to load during the delay
Show the main layout when the delay is over
But, the problem is that the thing need to be loaded is UI which requires to do that in the main thread, not in a background thread. So, we instead of using two different layout and call setContentView() twice; you could instead create a single layout for your main layout, and add some view that represents the splash screen which will obscure the main layout entirely (be in front of it) until the layout is loaded (i.e. the delay is over); then remove this splash view then:
Demo:
splash_screen.xml (Any layout you want that must match parent to obscure it):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/splash_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
android:gravity="center">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher" />
</LinearLayout>
Main activity:
class MainActivity : AppCompatActivity() {
companion object {
const val TAG = "LOG_TAG"
}
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "Start Inflating layout")
binding = DataBindingUtil.setContentView(
this#MainActivity,
R.layout.activity_main
)
// Show only the first time app launches, not in configuration changes
if (savedInstanceState == null) {
CoroutineScope(IO).launch {
Log.d(TAG, "Start of delay")
delay(1000)
Log.d(TAG, "End of delay")
withContext(Main) {
hideSplash()
}
}
showSplash()
}
binding.lifecycleOwner = this#MainActivity
Log.d(TAG, "End Inflating layout")
}
private fun showSplash() {
supportActionBar?.hide()
// Inflate splash screen layout
val splashLayout =
layoutInflater.inflate(
R.layout.splash_screen,
binding.rootLayout,
false
) as LinearLayout
binding.rootLayout.addView(
splashLayout
)
}
private fun hideSplash() {
supportActionBar?.show()
binding.rootLayout.removeView(
findViewById(R.id.splash_screen)
)
}
}
Logs
2021-12-11 21:59:18.349 20681-20681/ D/LOG_TAG: Start Inflating layout
2021-12-11 21:59:18.452 20681-20707/ D/LOG_TAG: Start of delay
2021-12-11 21:59:18.476 20681-20681/ D/LOG_TAG: End Inflating layout
2021-12-11 21:59:20.457 20681-20707/ D/LOG_TAG: End of delay
Now the delay is running along with inflating the layout; the splash screen shown while it loads; and ends when the delay is over.
UPDATE 2
It's definitely not going to work: databinding = ... line takes 2.5 seconds to complete, can't add a view to "databinding.root" before it's ready. It works in the presented code because your main view is tiny.
Now try to separate inflating the layout from setContentView() in dataBinding; still both requires to be in the main thread
setContentView(R.layout.screen_splash)
CoroutineScope(Main).launch {
// Inflate main screen layout asynchronously
binding = ActivityMainBinding.inflate(layoutInflater)
delay(2500) // 2.5 sec delay of loading the mainLayout before setContentView
setContentView(binding.root)
binding.lifecycleOwner = this#MainActivity
}
Finally found the problem and, in retrospect, it was too elementary for the question:
Must assign ViewModel before lifecycleOwner
binding.viewModel = myViewModer
binding.livecycleOwner = this#MainActivity
Just changing order of these lines fixed it.
Related
RecycleView Scroll Issue When Add New Row On Bottom In Android
I have a simple chat application on Android, in that one is the chat screen, After loading the initial chat message look like recycle view filled up with conversion and hold at the bottom end scroll position. Now I have a new message(either I post / from an opponent user) that scrolls to the last message which is fine. Now I scroll above to see history conversion to read the past messages, and while reading I got a new 2-3 message from my opponent user and my scroll view bounce up down and not hold its scroll position. Look at the screenshot I attached After the new message insert, I will update the adapter like private fun notifyAdapter() { try { val recyclerViewState = rvGroupChatMessages.layoutManager?.onSaveInstanceState() messageAdapter.notifyDataSetChanged() rvGroupChatMessages.layoutManager?.onRestoreInstanceState(recyclerViewState) } catch (e: Exception) { e.printStackTrace() } }
I recommend you to use DiffUtil and also try using the sample code below. recyclerView.post { recyclerView.scrollToPosition(messageAdapter.itemCount - 1) }
<androidx.recyclerview.widget.RecyclerView android:id="#+id/rvGroupChatMessages" android:layout_width="match_parent" android:layout_height="0dp" android:scrollbars="vertical" android:fitsSystemWindows="true" android:descendantFocusability="blocksDescendants" app:layout_constraintBottom_toBottomOf="#+id/cvBottomLayout" app:layout_constraintBottom_toTopOf="#id/cvBottomLayout" app:layout_constraintTop_toTopOf="parent" /> Try this : android:descendantFocusability="blocksDescendants" If you are using ConstraintLayout make sure RecyclerView height is 0dp
Data-binding on BottomSheetDialog Layout (Crash)
I am having trouble getting data-binding to work properly on a BottomSheetDialog layout. Here are the details: Definition and setting of var: private lateinit var myDrawerBinding: MyDrawerBinding myDrawerBinding = MyDrawerBinding.bind(myDrawerContent) // crashes on this line and later it's set and shown this way (although it never gets to this point) myDrawerBinding.viewModel = theViewModel val bottomSheet = BottomSheetDialog(context) bottomSheet.setContentView(myDrawerBinding.myDrawerContent) bottomSheet.show() Here is a snippet of the XML layout (my_drawer.xml): <?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <import type="android.view.View"/> <variable name="viewModel" type="path.to.my.viewModel"/> </data> <RelativeLayout android:id="#+id/myDrawerContent" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp"> <View android:layout_width="50dp" android:layout_height="3dp" android:visibility="#{viewModel.shouldShowView() ? View.VISIBLE : View.GONE}"/> .... The crash occurs when it calls the .bind() method above, and the error is: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.view.View.getTag()' on a null object reference This same exact functionality works on a separate DrawerLayout that I am showing in the same Fragment, but for some reason the BottomSheetDialog layout is giving problems.
Finally found a fix for this. I had to treat this view a little differently from my DrawerLayout, although I have a feeling this approach may work for that view as well. Here is the binding setup: val myDrawerView = layoutInflater.inflate(R.layout.my_drawer, null) val binding = MyDrawerBinding.inflate(layoutInflater, myDrawerView as ViewGroup, false) binding.viewModel = theViewModel And then to show the view: val bottomSheetDialog = BottomSheetDialog(context) bottomSheetDialog.setContentView(binding.myDrawerContent) bottomSheetDialog.show() Works like a charm now!
Mapbox map only semi responds to panning gestures
I have implements a mapbox MapView. It appears on screen just fine, but when I try to pan the map around, it kinds moves a few pixels on the screen in the direction I intended and then it stop while my finger is still sliding. Sometimes that would happen and sometimes it wouldn't respond at all. When it stops, it doesn't mean it is stuck now - I can try again and it might move again but the same way. It's very unpredictable, not consistent and clunky. **I have to mention, that double click for zooming always works. So it's something with the swipe gesture that doesn't sit well. I have the map hosted in a fragment and I show in in a frame inside another fragment. Could it have anything to do to the fact that it's two layers of fragment managers (fragment within fragment). This is my map's fragment xml: <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:mapbox="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".fragments.ImageMapViewFragment" tools:showIn="#layout/fragment_image_expanded"> <com.mapbox.mapboxsdk.maps.MapView android:id="#+id/mapView" android:layout_width="match_parent" android:layout_height="match_parent" mapbox:mapbox_cameraZoom="11"/> </androidx.constraintlayout.widget.ConstraintLayout> This is my fragment: mapView = view.findViewById(co.getdere.R.id.mapView) mapView?.getMapAsync { mapboxMap -> mapboxMap.setStyle(Style.LIGHT) { style -> style.addImage( DERE_PIN, BitmapUtils.getBitmapFromDrawable(resources.getDrawable(R.drawable.pin_icon))!!, true ) val geoJsonOptions = GeoJsonOptions().withTolerance(0.4f) val symbolManager = SymbolManager(mapView!!, mapboxMap, style, null, geoJsonOptions) symbolManager.iconAllowOverlap = true sharedViewModelForImage.sharedImageObject.observe(this, Observer { it?.let { image -> val symbolOptions = SymbolOptions() .withLatLng(LatLng(image.location[0], image.location[1])) .withIconImage(DERE_PIN) .withIconSize(1.3f) .withZIndex(10) .withDraggable(true) symbolManager.create(symbolOptions) val position = CameraPosition.Builder() .target(LatLng(image.location[0], image.location[1])) .zoom(10.0) .build() mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(position)) } }) } } These are my dependencies (the last I've added trying to solve my problem but it remains, that dependency didn't change anything really) implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:7.4.0-alpha.1' implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-annotation-v7:0.6.0' implementation 'com.mapbox.mapboxsdk:mapbox-android-gestures:0.4.0'
My problem was that even though my fragment was external, it was hosted inside a scroll layout so the gestures were lost between the two view probably
ConstraintLayout intermittent layout failure
ConstraintLayout intermittently fails to layout correctly when a view is set from GONE to VISIBLE shortly after an activity is resumed: <android.support.constraint.ConstraintLayout android:id="#+id/constraint_layout" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="#string/appbar_scrolling_view_behavior"> <TextView android:id="#+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent"/> <TextView android:id="#+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintLeft_toRightOf="#id/text1" app:layout_constraintTop_toTopOf="parent"/> </android.support.constraint.ConstraintLayout> override fun onResume() { super.onResume() text1.text = "" text1.visibility = View.GONE text2.text = "" text2.visibility = View.GONE text1.postDelayed({ text1.text = "Hello" text1.visibility = View.VISIBLE text2.text = "World" text2.visibility = View.VISIBLE }, 100 ) } Full source code here Instrumenting the TextView class reveals that the TextView instances are measured correctly but their width is set to 0 when they are laid out. I wonder if the ConstraintLayout LinearSystem is non-deterministic. Are there maps that are iterated over where the iteration order is undefined? (I've seen this with Cassowary)
I'm looking to your statement in github page: ConstraintLayout intermittently fails to layout correctly when a view is set from GONE to VISIBLE shortly after an activity is resumed I've checked out your project and changed 100ms to 1000ms. Here's the output: It seems to me, that you expect that the moment you perform textview.setVisibility(View.GONE) you expect the view to be not visible. That's not the way android works. You are merely posting an event to the MessageQueue that would be handled later by Looper, and this 100ms is not enough for human eye to see those changes happening.
This was a bug in the ConstraintLayout fixed in constraint-layout:1.1.0-beta2 https://issuetracker.google.com/issues/65613481
android.view.InflateException: Binary XML file: Error inflating class fragment
I have a very frustrating error that I cannot explain. I created an Android application that uses Android AppCompat to make it compatible with older versions. Here is my main activity layout file: <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- As the main content view, the view below consumes the entire space available using match_parent in both dimensions. --> <FrameLayout android:id="#+id/container" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- android:layout_gravity="start" tells DrawerLayout to treat this as a sliding drawer on the left side for left-to-right languages and on the right side for right-to-left languages. If you're not building against API 17 or higher, use android:layout_gravity="left" instead. --> <!-- The drawer is given a fixed width in dp and extends the full height of the container. --> <fragment android:id="#+id/navigation_drawer" android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent" android:layout_gravity="start" android:name="com.fragment.NavigationDrawerFragment" /> </android.support.v4.widget.DrawerLayout> And here is main code of my activity : public class MainActivity extends ActionBarActivity { #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } The main problem here is : above code run smoothly on almost devices (stimulated device, or some real devices). But when I run it on Samsung S3. It notices this error: java.lang.RuntimeException: Unable to start activity ComponentInfo{view.MainActivity}: android.view.InflateException: Binary XML file line #25: Error inflating class fragment at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2081) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2106) at android.app.ActivityThread.access$700(ActivityThread.java:134) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1217) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4856) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774) at dalvik.system.NativeStart.main(Native Method) Caused by: android.view.InflateException: Binary XML file line #25: Error inflating class fragment at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) at android.view.LayoutInflater.inflate(LayoutInflater.java:489) at android.view.LayoutInflater.inflate(LayoutInflater.java:396) at android.view.LayoutInflater.inflate(LayoutInflater.java:352) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:316) at android.app.Activity.setContentView(Activity.java:1901) at android.support.v7.app.ActionBarActivity.superSetContentView(ActionBarActivity.java:208) at android.support.v7.app.ActionBarActivityDelegateICS.setContentView(ActionBarActivityDelegateICS.java:111) at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:76) Please tell me how to fix error, thanks :)
After long time for debugging, I have fixed this problem. (Although I still cannot explain why). That I change property android:name to class. (although on Android Document, they say those properties are same, but it works !!!) So, it should change from : android:name="com.fragment.NavigationDrawerFragment" to class = "com.fragment.NavigationDrawerFragment" So, new layout should be : <!-- As the main content view, the view below consumes the entire space available using match_parent in both dimensions. --> <FrameLayout android:id="#+id/container" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- android:layout_gravity="start" tells DrawerLayout to treat this as a sliding drawer on the left side for left-to-right languages and on the right side for right-to-left languages. If you're not building against API 17 or higher, use android:layout_gravity="left" instead. --> <!-- The drawer is given a fixed width in dp and extends the full height of the container. --> <fragment android:id="#+id/navigation_drawer" android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent" android:layout_gravity="start" class = "com.fragment.NavigationDrawerFragment" /> Hope this help :)
TL/DR: An exception occurred during the creation of a fragment referenced from a higher-level layout XML. This exception caused the higher-level layout inflation to fail, but the initial exception was not reported; only the higher-level inflation failure shows up in the stack trace. To find the root cause, you have to catch and log the initial exception. The initial cause of the error could be a wide variety of things, which is why there are so many different answers here as to what fixed the problem for each person. For some, it had to do with the id, class, or name attributes. For others it was due to a permissions issue or a build setting. For me, those didn't fix the problem; instead there was a drawable resource that existed only in drawable-ldrtl-xhdpi, instead of in an applicable place like drawable. But those are just details. The big-picture problem is that the error message that shows up in logcat doesn't describe the exception that started it all. When a higher-level layout XML references a fragment, the fragment's onCreateView() is called. When an exception occurs in a fragment's onCreateView() (for example while inflating the fragment's layout XML), it causes the inflation of the higher-level layout XML to fail. This higher-level inflation failure is what gets reported as an exception in the error logs. But the initial exception doesn't seem to travel up the chain well enough to be reported. Given that situation, the question is how to expose the initial exception, when it doesn't show up in the error log. The solution is pretty straightforward: Put a try/catch block around the contents of the fragment's onCreateView(), and in the catch clause, log the exception: public View onCreateView(LayoutInflater inflater, ViewGroup contnr, Bundle savedInstSt) { try { mContentView = inflater.inflate(R.layout.device_detail_frag, null); // ... rest of body of onCreateView() ... } catch (Exception e) { Log.e(TAG, "onCreateView", e); throw e; } } It may not be obvious which fragment class's onCreateView() to do this to, in which case, do it to each fragment class that's used in the layout that caused the problem. For example, in the OP's case, the app's code where the exception occurred was at android.app.Activity.setContentView(Activity.java:1901) which is setContentView(R.layout.activity_main); So you need to catch exceptions in the onCreateView() of any fragments referenced in layout activity_main. In my case, the root cause exception turned out to be Caused by: android.content.res.Resources$NotFoundException: Resource "com.example.myapp:drawable/details_view" (7f02006f) is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f02006f a=-1 r=0x7f02006f} This exception didn't show up in the error log until I caught it in onCreateView() and logged it explicitly. Once it was logged, the problem was easy enough to diagnose and fix (details_view.xml existed only under the ldrtl-xhdpi folder, for some reason). The key was catching the exception that was the root of the problem, and exposing it. It doesn't hurt to do this as a boilerplate in all your fragments' onCreateView() methods. If there is an uncaught exception in there, it will crash the activity regardless. The only difference is that if you catch and log the exception in onCreateView(), you won't be in the dark as to why it happened. P.S. I just realized this answer is related to #DaveHubbard's, but uses a different approach for finding the root cause (logging vs. debugger).
I couldn't solve my problem using provided answers. Finally I changed this: <fragment android:id="#+id/fragment_food_image_gallery" android:name="ir.smartrestaurant.ui.fragment.ImageGalleryFragment" android:layout_width="match_parent" android:layout_height="200dp" android:layout="#layout/fragment_image_gallery" tools:layout="#layout/fragment_image_gallery" /> to this : <FrameLayout android:id="#+id/fragment_container" android:layout_width="match_parent" android:layout_height="200dp" /> , private void showGallery() { ImageGalleryFragment fragment = new ImageGalleryFragment() getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, fragment) .commit(); } and it works. If you are using it inside fragment, use getChildFragmentManager instead of getSupportFragmentManager.
I had the same problem, issue, tried all the answers in this thread to no avail. My solution was, I hadn't added an ID in the Activity XML. I didn't think it would matter, but it did. So in the Activity XML I had: <fragment android:name="com.covle.hellocarson.SomeFragment" android:layout_width="wrap_content" android:layout_height="wrap_content"/> But should've had: <fragment android:id="#+id/some_fragment" android:name="com.covle.hellocarson.SomeFragment" android:layout_width="wrap_content" android:layout_height="wrap_content"/> If someone would be happy to comment on why this is, I'm all ears, to other, I hope this helps.
It might not be needed for you anymore, but if further readers find it helpful. I have exact same android.view.InflateException:...Error inflating class fragment. I had all right libraries included. Solved by adding one more user permission in the AndroidManifest.xml file i.e. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> Btw I was running Android Studio 0.8.9 on Ubuntu 12.04.
I have the same problem because I did not implement the listener. See the following code with /*Add This!*/. public class SomeActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener /*Add this!*/ { #Override /*Add This!*/ public void onFragmentInteraction(Uri uri){ /*Add This!*/ } /*Add This!*/ } FYI, my fragment class is something like the following: public class SomeFragment extends Fragment { private OnFragmentInteractionListener mListener; #Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } public interface OnFragmentInteractionListener { public void onFragmentInteraction(Uri uri); } } Edit: I also notice this same error message under another circumstances when there is an exception in the onCreate function of the Fragment. I have something as the following: #Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); int ID = getArguments().getInt("val"); return rootView; } Because I reuse this fragment, I total forget to set arguments. Then the result of getArguments() is null. Obviously, I get a null pointer exception here. I will suggest you keep an eye on mistakes like this as well.
Is your NavigationDrawerFragment extending the android.support.v4.app.Fragment? In other words, are you importing the correct package? import android.support.v4.app.Fragment;
I also had this issue. I solved it by replacing the import in MainActivity and NavigationDrawerFragment From import android.app.Activity; import android.app.ActionBar; To import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; I updated MainActivity to extends ActionBarActivity instead of Activity public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks Also use ActionBar actionBar = getSupportActionBar(); to get the ActionBar And I updated the following function in NavigationDrawerFragment private ActionBar getActionBar() { return ((ActionBarActivity)getActivity()).getSupportActionBar(); }
i faced this problem and solved it by using following codes. I was beginning fragment transaction by using childfragment manager. layout: <fragment class="com.google.android.youtube.player.YouTubePlayerSupportFragment" android:id="#+id/youtube_fragment" android:layout_width="match_parent" android:layout_height="wrap_content"/> this is how i began fragment transaction: youTubePlayerFragment = (YouTubePlayerSupportFragment) getChildFragmentManager().findFragmentById(R.id.youtube_fragment); the following codes explains how i removed the fragment which added by using childfragmentmanger. #Override public void onDestroyView() { super.onDestroyView(); youTubePlayerFragment = (YouTubePlayerSupportFragment) getChildFragmentManager().findFragmentById(R.id.youtube_fragment); if (youTubePlayerFragment != null) { getChildFragmentManager().beginTransaction().remove(youTubePlayerFragment).commitAllowingStateLoss(); } youTubePlayer = null; }
I have had similar problems on and off. The error message often provides very little detail, regardless of actual cause. But I found a way to get more useful info. It turns out that the internal android class 'LayoutInflater.java' (in android.view package) has an 'inflate' method that re-throws an exception, but does not pick up the details, so you lose info on the cause. I used AndroidStudio, and set a breakpoint at LayoutInflator line 539 (in the version I'm working in), which is the first line of the catch block for a generic exception in that 'inflate' method: } catch (Exception e) { InflateException ex = new InflateException( parser.getPositionDescription() + ": " + e.getMessage()); ex.initCause(e); throw ex; If you look at 'e' in the debugger, you will see a 'cause' field. It can be very helpful in giving you a hint about what really occurred. This is how, for example, I found that the parent of an included fragment must have an id, even if not used in your code. Or that a TextView had an issue with a dimension.
Just in case someone needs this. Assumptions: Device phone hooked up to USB cable and your IDE reading to launch the app. Go to the command prompt to determine issue: enter adb logcat Then launch your app from IDE. You will an exception. In my case: I was deploying an Android app of Version 2.3 to a mobile device that did not support the widget "Space"
Add this name field in navigation android:name="androidx.navigation.fragment.NavHostFragment" <fragment android:id="#+id/container" android:layout_width="match_parent" android:layout_height="0dp" android:name="androidx.navigation.fragment.NavHostFragment" app:navGraph="#navigation/navigation" app:layout_constraintBottom_toTopOf="#+id/bottomNavigationView" app:layout_constraintTop_toTopOf="parent">
This problem arises when you have a custom class that extends a different class (in this case a view) and does not import all the constructors required by the class. For eg : public class CustomTextView extends TextView{} This class would have 4 constructors and if you miss out on any one it would crash. For the matter of fact I missed out the last one which was used by Lollipop added that constructor and worked fine.
we must also need to add following in build.gradle(app) compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1' whenever we are using new layouts or new design features. hope this helps you.
As mentioned in a previous post, rename android:name="com.fragment.NavigationDrawerFragment" to class = "com.fragment.NavigationDrawerFragment" Still, it did not work for me. I then just used the Class Name without the com.fragment part and voila it worked. So change it finally to class = "NavigationDrawerFragment"
After none of the answers here helped me, I opted to run app in debug mode moving across every line of onCreateView in my fragment (NavigationDrawerFragment in your case). And noticed that fragment was having difficulty with inflating because of a NullPointerException. E.g. mySeekBar = (SeekBar) getActivity().findViewById(R.id.mySeekBar); mySeekBar.setOnSeekBarChangeListener(this); Here mySeekBar was set to null (because I had missed adding the control in appropriate layout) and the next line got into NPE which came out as InflateException. Also, as suggested above, rename android:name to class. This issue can arise for various reasons mentioned above. I would recommend line-by-line debug flow to know what is wrong.
After long time of tries, this is how I solved the problem after none of the above answers could. Extend AppCompatActivity for your Main activity instead of Activity. Add android:theme="#style/Theme.AppCompat.Light" to your <Activity..../> in the AndroidManifest.xml In your NavigationDrawerFragment Class, change your ActionBar instances to ActionBar mActionBar=((AppCompatActivity)getActivity()).getSupportActionBar(); EDIT It should be a consistency between the Activity and Layout. If the Layout has one of the AppCompat Theme such like Theme.AppCompat.Light, your Activity should extends AppCompatActivity. I wanted to have the burger icon and a Navigation Drawer that looks like the Android Gmail App, but I ended up with an ugly Navigation Drawer. All that because all my Classes extends Activity instead of AppCompatActivity. I re-factored the entire project to extend AppCompatActivity, then Right-Click on the Layout Folder, chose new -> Activity then Navigation Drawer Activity and Boom, everything is done for me!
android.view.InflateException: Binary XML file line #16: Error inflating class com.google.android.material.bottomappbar.BottomAppBar The view can be anything that is failing to get inflated, this kind of error comes when there is a clash in resolving the class names or name attribute of a view referred in the XML file. When I get the same error I just got everything clean and safe in UI-XML file, the view I was using, <com.google.android.material.bottomappbar.BottomAppBar android:id="#+id/bottomAppBar" style="#style/Widget.MaterialComponents.BottomAppBar.Colored" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" app:hideOnScroll="true" app:menu="#menu/bottom_app_bar" app:navigationIcon="#drawable/ic__menu_24"/> I was using a style attribute which was referring the Material components property. But my styles.xml had... <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> .... </style> Where the class resolving was facing the conflict. My view attributes referred a property that was not defined in my app theme. The right parent theme from material components helped me. So I changed the parent attribute to... <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> ... </style> Which resolved the issue.
For some of you that still haven't found a solution for this, in my case it was happening because I had an OOM (Out of Memory) issue. This can happen when you have for example a memory leak in your app when using it for a long time. In my stack trace, this was the main reason.
I don't know if this will help. I had this problem with a TextView I had in the layout I was trying to inflate (android.view.InflateException: Binary XML file line #45: Error inflating class TextView). I had set the following XML attribute android:textSize="?android:attr/textAppearanceLarge" which wasn't allowing for the layout to be inflated. Don't know exactly why, (I'm still a bit new to Android - less than a year of experience), might have something to do with calling system attributes, idk, all I know is as soon as I used plain old #dimen/md_text_16sp (which is a custom of mine), problem solved :) Hope this helps...
I had this on a 4.4.2 device, but 5+ was fine. The cause: inside a custom view's initialisation, I was creating a TextView(Context context, AttributeSet attrs, #AttrRes int defStyleAttr, #StyleRes int defStyleRes), which is API 21+. Android Studio 2.1 doesn't complain about it even though it is annotated TargetApi(21). Apparently, Android Studio 2.2 will correct this and properly show it as an error. Hope this helps someone.
I am a bit late to the party but Non of these answer helped me in my case. I was using Google map as SupportMapFragment and PlaceAutocompleteFragment both in my fragment. As all the answers pointed to the fact that the problem is with SupportMapFragment being the map to be recreated and redrawn. But I also had problem with PlaceAutocompleteFragment. So here is the working solution for those who are facing this problem because of SupportMapFragment and SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFragment); FragmentManager fm = getChildFragmentManager(); if (mapFragment == null) { mapFragment = SupportMapFragment.newInstance(); fm.beginTransaction().replace(R.id.mapFragment, mapFragment).commit(); fm.executePendingTransactions(); } mapFragment.getMapAsync(this); //Global PlaceAutocompleteFragment autocompleteFragment; if (autocompleteFragment == null) { autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autoCompleteFragment); } And in onDestroyView clear the SupportMapFragment and SupportMapFragment #Override public void onDestroyView() { super.onDestroyView(); if (getActivity() != null) { Log.e("res","place dlted"); android.app.FragmentManager fragmentManager = getActivity().getFragmentManager(); android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.remove(autocompleteFragment); fragmentTransaction.commit(); autocompleteFragment = null; } }
In my particular case the problem was I added this line to a TextView : android:background="?attr/selectableItemBackground" After removing this, everything started to work fine.
I don`t know what happened, but Changing Fragment to FrameLayout solved my problem after many hours of struggle. <FrameLayout android:id="#+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" />
I think the basic problem is with "android:targetSdkVersion" which is defined in AndroidManifest.xml. In my case, the initial value which I have defined as: android:targetSdkVersion=16 I changed it to: android:targetSdkVersion=22 which resolved my all of the error. So, setting up the correct "targetSdkVersion" is also important before building an android app.
In case someone else comes here and the answers do not help solve the problem, one more thing to try. As others have mentioned, this usually is caused by an issue nested in the XML itself as opposed to something you did wrong in your Java. In my case, it was a super easy (and stupid) mistake to fix. I had code like this: <view android:layout_width="fill_parent" android:layout_height="1dip" android:id="#+id/view44" android:background="#color/gray" /> When all I had to do was capitalize the v in 'View' so that the system recogized it. Check that your custom views (Or Fragments, recyclerviews, etc) all have the proper capitalized declaration up front so that the XML auto-complete will match it to the appropriate view.
I had this error too, and after very long debugging the problem seamed to be that my MainClass extended Activity instead of FrameActivity, in my case, the xml wasn't a problem. Hope to help you.
In my case . The layout i was trying to inflate had <include layout = "...." /> tag, removing it fixed it. I was trying to inflate a previous layout designed for a Actvity into the view-pager adapter.
My error was caused by a different problem. I was passing a bundle from an Activity to its fragment. When I commented the code receiving the bundle in the fragment the error was gone. As it turns out, my error was due to the below "getArguments();" part which was returning null. Bundle args = getArguments(); Upon checking the Activity sending code, I realized I had a silly mistake in the below; Bundle bundle =new Bundle(); bundle.putInt("recipeID", recipe_position); Fragment mainFragment = new MainActivityFragment(); mainFragment.setArguments(bundle); FragmentManager fragmentManager = getSupportFragmentManager(); --> fragmentManager.beginTransaction() .replace(R.id.container, new MainActivityFragment(), DetailRecipeActivityFragment.TAG) .commit(); I was creating a NEW fragment in the line with the arrow. Whereas I should have used the pre-instantiated fragment that already had my bundle. So it should have been: Bundle bundle =new Bundle(); bundle.putInt("recipeID", recipe_position); Fragment mainFragment = new MainActivityFragment(); mainFragment.setArguments(bundle); Fragment mainFragment = new MainActivityFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); -->fragmentManager.beginTransaction() .replace(R.id.container, mainFragment, DetailRecipeActivityFragment.TAG) .commit(); I don't know why exactly it throws this error instead of an NPE, but this solved my error in case someone is having the same scenario
I was having the same problem, in my case the package name was wrong, fixing it solved the problem.