tsync
tsync

Reputation: 2417

Error inflating class fragment

I get the Error

Unable to start activity ComponentInfo{de.androidbuch.activiti/de.androidbuch.activiti.task.Activity}: android.view.InflateException: Binary XML file line #11: Error inflating class fragment

when I switch via the portrait and the landscape mode. I'm using fragments. My xml is:

 <LinearLayout android:id="@+id/mainLayout"
               android:orientation="horizontal"
               android:layout_width="fill_parent"
               android:layout_height="wrap_content" >

    <ListView android:id="@+id/android:list"
              android:layout_height="wrap_content"
              android:layout_width="fill_parent"/> 

    <fragment android:id="@+id/fragmentDetails"
              android:layout_height="fill_parent"
              android:layout_width="fill_parent"
              class="de.androidbuch.activiti.task.TaskDetailsFragment"/> 
</LinearLayout>

If I switch via landscape and portrait mode everything works fine. But when I click on my fragment (and I can see my fragment) and then switch to the other mode I get the error. Any idea how I can solve it? Found some answers here but none of these helped me out...

06-21 14:55:05.600: ERROR/AndroidRuntime(7636): FATAL EXCEPTION: main
06-21 14:55:05.600: ERROR/AndroidRuntime(7636): java.lang.RuntimeException: Unable to start activity         
ComponentInfo{de.androidbuch.activiti/de.androidbuch.activiti.task.Activity}:   android.view.InflateException: Binary XML file line #11: Error inflating class fragment
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1736)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1752)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3097)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.app.ActivityThread.access$1600(ActivityThread.java:123)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:997)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.os.Looper.loop(Looper.java:126)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.app.ActivityThread.main(ActivityThread.java:3998)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at java.lang.reflect.Method.invokeNative(Native Method)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at java.lang.reflect.Method.invoke(Method.java:491)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at dalvik.system.NativeStart.main(Native Method)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636): Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class fragment
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:688)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:724)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:727)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.view.LayoutInflater.inflate(LayoutInflater.java:391)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.view.LayoutInflater.inflate(LayoutInflater.java:347)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:227)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.app.Activity.setContentView(Activity.java:1771)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at de.androidbuch.activiti.task.TaskActivity.onCreate(TaskActivity.java:83)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1700)
06-21 14:55:05.600: ERROR/AndroidRuntime(7636):     ... 12 more

Upvotes: 188

Views: 369063

Answers (30)

Odysseus
Odysseus

Reputation: 1283

In my case the problem was using a FragmentStateAdapter in a top-fragment which initializes some sub-fragments with an interface like:

class TopFragment: Fragment(), SubFragmentListener {

   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       // ...
       viewPager.adapter = MyFragmentAdapter(this)
   }
}

class MyFragmentAdapter(fragment: TopFragment): FragmentStateAdapter(fragment) {
   private val _fragment = fragment

   override fun createFragment(_: Int): Fragment {
       return SubFragment(_fragment)
   }
}

class SubFragment(listener: SubFragmentListener): Fragment() {
   var _listener = listener
   
   interface SubFragmentListener {
       fun onSomethingHappened()
   }
}

The problem in this case is MyFragmentAdapter::createFragment is only called once after my top fragment was created (and then with a valid argument) - which is fine.

But when changing from portrait to landscape - FragmentStateAdapter handles things differently and somehow restores the already created SubFragment resulting in its constructor being called with some invalid argument (probably with the old instance of TopFragment) leading also to the mentioned error message.

Upvotes: 0

Foroogh Varmazyar
Foroogh Varmazyar

Reputation: 1605

I get this error when start using Hilt. If you are using Hilt , sure that you declare your appliction class in your AndroidManifest.xml file, in the <application.../>tag , and annotate your application class with @HiltAndroidApp, and if you are use fragment, annotate your host activity by @AndroidEntryPoint

Upvotes: 0

Alan Maxwell
Alan Maxwell

Reputation: 71

In my case the problem started to happen after the target activity movement. The reason was in Android databinding - previously it generated intermediate classes and after activities classes movements these intermediate files remained. Cleaning of the project helped.

Upvotes: 0

Fakhriddin Abdullaev
Fakhriddin Abdullaev

Reputation: 4940

Use androidx.fragment.app.FragmentContainerView instead of fragment. Here is a example:

 <androidx.fragment.app.FragmentContainerView 
          android:id="@+id/fragmentDetails"
          android:layout_height="fill_parent"
          android:layout_width="fill_parent"
          class="de.androidbuch.activiti.task.TaskDetailsFragment"/> 

Upvotes: 4

Amr
Amr

Reputation: 1342

My problem was that I am adding Google maps API key in the value folder! move it to src/debug/res/values/sensitive_keys.xml

Upvotes: 0

QuartZ
QuartZ

Reputation: 164

I want to add a possible answer. So here we go.

My situation is, I change my project from Java to Kotlin, and then add Navigation Component. After migrating to Kotlin, then I add the nav_graph.xml. But, after try running the app, I got an inflating error. After checking further and comparing to other projects, turn out My nav_graph.xml did not have app:startDestination="@id/mainFragment". After adding app:startDestination, the error went away and my project runs just fine with no error.

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/mainFragment">
    <fragment
        android:id="@+id/mainFragment"
        android:name="fragment.MainFragment"
        android:label="fragment_main"
        tools:layout="@layout/fragment_main" />
</navigation>

So, don't forget the app:startDestination.

Upvotes: 2

Kolaaa
Kolaaa

Reputation: 256

For me, refactored code caused the problem. I moved a fragment into a new package and one of the references in the xml file caused the bug. So inspect your code very well

Upvotes: 0

Matiss
Matiss

Reputation: 5349

I had the same error. I was digging all day long, don't know but I think I tried ~25 solutions on this problem. None worked until at 2AM I found out that I was missing this line at apps manifest xml:

<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />

That line was inside <application> tag. I really hope this helps for someone. GL.

Upvotes: 46

Ben Butterworth
Ben Butterworth

Reputation: 28998

I did not have the androidx.fragment:fragment dependency.

You can get the latest version from the Jetpack/ AndroidX docs:

dependencies {
    def fragment_version = "1.2.5"

    // Java language implementation
    implementation "androidx.fragment:fragment:$fragment_version"
    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    // Testing Fragments in Isolation
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}

Upvotes: 1

ghost deathrider
ghost deathrider

Reputation: 151

I added an id to my fragment that's it everything works fine. Before this, I changed the manifests file as mentioned above but didn't solve my error. When you see error try to read it fully you'll get to know why there is an error. In my case, in the middle of the error trace, it was shown that the fragment id is missing.

<fragment
       android:layout_width="0dp"
       android:layout_weight="2"
       android:layout_height="match_parent"
       class="com.example.mydemofragmentapp.FoodListFragment"
       android:id="@+id/none"/>

Upvotes: 2

user3193413
user3193413

Reputation: 654

If you use obfuscation with Navigation component you need to exclude android's fragment and your args. Add these lines to your proguard-rules files:

# Exclude the fragments and argType for navigation component.
-keep class * extends androidx.fragment.app.Fragment{}
-keep class com.safetonet.presentation.features.parent.adddevice.model.PresentableAddDeviceData

Upvotes: 1

Peter Akwa
Peter Akwa

Reputation: 115

This is one of the errors you could get If your activity is not registered on the manifest. Check and ensure that your activity is registered on the manifest, that could be the possible cause of your error.

Upvotes: -1

Eduard  Fomin
Eduard Fomin

Reputation: 31

Here is my solution to this problem.

Caused by: android.view.InflateException: Binary XML file line #31: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #31: Duplicate id 0x7f09006d, tag null, or parent id 0xffffffff with another fragment for com.example.eduardf.audit.DateTime

In my case, the error occurred when re-opening the DialogFragment with a Fragment.

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableStart="@drawable/ic_black_edit_24px"
            android:singleLine="true" />
        <fragment
            android:id="@+id/fragment_date"
            android:name="com.example.eduardf.audit.DateTime"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:layout="@layout/fragment_date_time" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

DailogFragment stores the fragment after the first inflate. To prevent this from happening, I forcibly deleted the fragment.

@Override
public void onDestroyView () {
    if (!(afterRotate || getActivity() == null)) {
        final FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        final Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_date);
        if (fragment != null)
            fragmentManager.beginTransaction().remove(fragment).commit();
    }
    super.onDestroyView();
}

Also had to take care of unnecessary removal of the fragment, for example, when you rotate the screen.

private boolean afterRotate = false;
...
@Override
public void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    afterRotate = true;
}

Upvotes: 0

Sankha Pattanayak
Sankha Pattanayak

Reputation: 21

Make sure You have put your google-services.json on your respective folder and oviously add

<meta-dataandroid:name="com.google.android.geo.API_KEY" android:value="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" />

in your manifest file. Check your gradle with "implementation 'com.google.android.gms:play-services-maps:15.0.1'"

It will work.

Upvotes: 0

Sahaj Rana
Sahaj Rana

Reputation: 2013

If you don't want to change anything and go with "fragment" tag

do this,

<fragment
 android:visibility="gone" (Visibility will not work, just helps in removing frag from xml viewer)(If you want the visibility to be gone make it in your fragment root element visibility=gone)
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:name="com.example.YOUR_FRAGMENT" (This is important)
 />

Upvotes: 4

Santosh Kumar
Santosh Kumar

Reputation: 205

My simple approach

If you use <fragment> in your xml then you must provide name attribute i.e;

      <fragment 
        android:name='path.to.your.fragment
        />`

which will initialise your fragment and you don't need to do it from java.

If you want to use Java approach to add fragment then, use any layout like

<LinearLayout
   android:id="@+id/fragment_container"
 />

and use this container for your fragment

transaction.replace(R.id.fragment_container, fragment_obj);

Upvotes: 0

xMythicx
xMythicx

Reputation: 827

I was receiving this error for different reasons.

Steps to reproduce:

~> My issue was that I created a brand new blank application.

~> I then generated a custom fragment from the File ~> New File Menu.

~> Proceeded to customize the fragment by adding layouts and buttons etc.

~> Referenced the new custom fragment in the auto generated activity_my.xml that was generated for me when creating the application. Doing this allowed the XML to generate the objects for me.

Heres is the catch when generating the custom fragment via File ~> New File Menu it auto generates an interface function stub and places it at the bottom of the fragment class file.

This means that your MyActivity class must implement this interface. If it does not then the the above error occurs only when referencing the fragment from xml. By removing the reference for the Fragment in the XML completely, and creating the fragment through code in the MyActivity.java class file Logcat generates a more concise error explaining the issue in detail and complaining about the interface. This is demonstrated in the Project Template Activity+Fragment. Although, <~that Project Template does not generate the interface stub.

Upvotes: 6

user2270629
user2270629

Reputation: 144

I had a similar problem; after running the AdMob example, I tried to insert Ads in my app, causing this error:

01-02 16:48:51.269    8199-8199/it.dndc.BreathPlot E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
 Caused by: android.view.InflateException: Binary XML file line #57: Error inflating class fragment

The solution is: you cannot insert the fragment for an Ad into a ListActivity. Instead, I could add it to a FragmentActivity and to an ActionBarActivity without any problem.

My suggestion is: start from the AdMob example and add into it your existing app: I would have saved a lot of time !!!

Upvotes: 1

Khushboo
Khushboo

Reputation: 3173

None of the solutions mentioned above helped me. In the log I could find the detail of the exception as mentioned below:

06-19 16:20:37.885: E/AndroidRuntime(23973): Caused by: java.lang.RuntimeException: API key not found.  Check that /meta-data/ android:name="com.google.android.maps.v2.API_KEY" android:value="your API key"/ is in the application element of AndroidManifest.xml.

I did this and my code was working!

<meta-data  android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyCl1yGPZ3mpxxxxxxxAz2R-t7zcWVzrHUL9k"/>
</application>

Upvotes: 3

Yogesh Rathi
Yogesh Rathi

Reputation: 6509

After one day struggle i found some scenario check may be you are facing same,

If everything is woking same as google code then please check manifest file in my case i added geo key and map key that's why exception occurs,

Note - do not add two keys in manifest file remove map key

meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="@string/google_maps_key"/>

above code and add this code.

 <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/auto_location"/>

 <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version"/>

Upvotes: 1

TonnyTao
TonnyTao

Reputation: 532

In my case,

...
android.view.InflateException: 
Binary XML file line #24: Error inflating class fragment
...
Caused by: java.lang.InstantiationException: 
class *.HomeFragment has no zero argument constructor
...

After I added the empty constructor, it's resolved.

public HomeFragment() {}

Upvotes: 0

Shaheer Palollathil
Shaheer Palollathil

Reputation: 313

If you are adding Fragment statically that is, in xml, then you might have missed to implement OnFragmentInteractionListener in your Activity class. Then the interface implementation would solve the problem. If you are adding Fragment dynamically, that is, in java class then this is not the solution. Because IDE itself will not allow you to proceed without implementing required interfaces.

Upvotes: 4

Lei
Lei

Reputation: 699

Make sure there is no exception raised in the onCreateView method of the fragment. If any exception is raised in this method, logcat won't show exact details of the exception, instead it always shows the message:

Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.fragment" 
on path: DexPathList[[zip file "/data/app/com.package/base.apk"],
nativeLibraryDirectories=[/data/app/com.package/lib/arm64, /vendor/lib64, /system/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)

Upvotes: 12

stevethecollier
stevethecollier

Reputation: 1034

I got the same error, but my issue was that my fragment did not have an id in the xml layout of the parent activity.

Upvotes: 1

Nuwan Karunarathna
Nuwan Karunarathna

Reputation: 428

If your fragment is a List Fragment then the activity which uses that fragment must implement the onFragmentInteraction interface.

Upvotes: 0

Riyas PK
Riyas PK

Reputation: 3217

Make sure your Activity extends FragmentActivity or AppCompatActivity

Upvotes: 1

Vaibhav Sharma
Vaibhav Sharma

Reputation: 2319

If you want to inherit the AppCompatActivity, then you can do something like this- In the activity xml, use a FrameLayout like this-

<FrameLayout
    android:id="@+id/result_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/progress_frame"/>

and in the activity onCreate-

final FragmentManager supportFragmentManager = getSupportFragmentManager();
    FragmentTransaction ft = supportFragmentManager.beginTransaction();
    ft.replace(R.id.result_fragment, fphResultActivityFragment, "result fragment");
    ft.commitAllowingStateLoss();

Upvotes: 2

Dandre Allison
Dandre Allison

Reputation: 6035

As hdemirchian said, make sure to use:

import android.support.v4.app.Fragment;

And also make sure that the Activity that is using the fragment(s) extends FragmentActivity instead of the regular Activity,

import android.support.v4.app.FragmentActivity;

to get the FragmentActivity class.

Upvotes: 133

Dhiraj Gupta
Dhiraj Gupta

Reputation: 10514

Fragments cannot be nested in XML

Learnt this the hard way - if you nest an XML layout based <fragment> tag inside a (potentially) dynamically loaded fragment from FragmentManager, then you start to get weird errors, trying to inflate your fragment xml.

Turns out, that this is not supported - it will work fine if you do this through purely the FragmentManager approach.

I was getting this problem because I was trying load a fragment inside a <DrawerLayout> from xml, and this was causing a crash in the onCreateView() method when I popped the back stack.

Upvotes: 19

Akshay
Akshay

Reputation: 35

Adding this to manifest solved my problem

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Upvotes: -10

Related Questions