[android] 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

This question is related to android android-layout android-fragments

The answer is


I was receiving this error in android studio the problem was that my fragment had a relative layout while the code on the OnCreateView function was

mDrawerListView = (ListView) inflater.inflate(
                R.layout.fragment_navigation_drawer, container, false);

is your code doing the same thing?


make sure that u have used this one

<meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyBEwmfL0GaZmdVqdTxxxxxxxx-rVgvY" />

not this..

<meta-data 
         android:name="com.google.android.gms.version" 
          android:value="AIzaSyBEwmfL0GaZmdVqdTCvxxxxxxx-rVgvY" /> 

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"/>

I had the same problem. The solution for me was the order of super.onCreate and setContentView within the FragmentActivity

Following order works fine:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.fc_activity_list_profiles);

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)
 />

Adding this to manifest solved my problem

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

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.


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.


Make sure your Activity extends FragmentActivity.


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.


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


Had the same error type, where exactly the same error message in logcat was displayed. I needed to make changes in the Java Build Path located under Project->Properties. I had included Google Maps related libraries like android-support-v4.jar and google-play-services.jar; however I was missing including these on the 'Build class path' in the 'Order and Export' option menu. Maybe the error lies here.

Try including libraries to the build class path.

The order of which the classes are built might also trigger the error, so my advice is also to try to rearrange the order of the building path. The error disappeared when I used the following order: 'my_project_name/src'->'my_project_name/gen'->'Android Private Libraries'. The last unit contains the jar files mentioned earlier.


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.


In your xml file just use a instead of the tag. The inflater tries to create an android.app.Fragment from which will fail on API < 10. So you need to create a view group of a different type.


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() {}

I got this error when using a ListFragment but the list view id was listView1 instead of list.

'Your content must have a ListView whose id attribute is 'android.R.id.list''

http://developer.android.com/reference/android/app/ListFragment.html


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)

For me it was after scrolling in the stack trace i found im missing the permission for android.permission.ACCESS_NETWORK_STATE

after adding this permission it was fixed


Have you tried:

 <fragment
            android:name="de.androidbuch.activiti.task.TaskDetailsFragment"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

I was having the same problem as you are facing. None of the tips on top helped me. Later, I found that all I had to do is fix my imports from:

import android.app.Fragment;

to:

import android.support.v4.app.Fragment;

My problem in this case was a simple instance of having a dumb null pointer exception in one of my methods that was being invoked later in the lifecycle. This was causing the "Error inflating class fragment" exception for me. In short, please remember to check the further down the exception stack trace for a possible cause.

Once I resolved the null pointer exception, my fragment loaded fine.


Could you post the fragment's onCreate and onCreateView methods? I had exactly same exception which was caused by an exception in the fragment onCreate method, when I fixed that problem it fixed the Error inflating class fragment.


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);

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 !!!


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;
}

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

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>

Check you class path, this could be the view inflator could not find your class definition as defined in your xml class="de.androidbuch.activiti.task.TaskDetailsFragment" the above path could be wrong.


The exception android.view.InflateException: Binary XML file line: #... Error inflating class fragment might happen if you manipulate with getActivity() inside your fragment before onActivityCreated() get called. In such case you receive a wrong activity reference and can't rely on that.

For instance the next pattern is wrong:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) 
{
    final View view = inflater.inflate(R.layout..., container, false);

    Button button = getActivity().findViewById(R.id...);
    button.setOnClickListener(...); - another problem: button is null

    return view;
}

Correct pattern #1

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) 
{
    final View view = inflater.inflate(R.layout..., container, false);

    Button button = view.findViewById(R.id...);
    button.setOnClickListener(...);

    return view;
}

Correct pattern #2

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Button button = getActivity().findViewById(R.id...);
    button.setOnClickListener(...);
}

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.


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.


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"/>

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.


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.


Make sure your Activity extends FragmentActivity or AppCompatActivity


If your TaskDetailsFragment extending android.app.Fragment, do change in onCreateView().

Return your view which you want to show in the Fragment or convert your Layout to view by using LayoutInflater and return it.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View mainview = inflater.inflate(R.layout.main, null);
    return mainview;
}

Hope this works. :)


Just had this same error. The reason for mine was the visibility of my fragment class. It was set to default, should be public.


If you have separate layout files for portrait and landscape modes and are getting an inflation error whenever you change orientation after clicking an item, there is most likely a discrepancy between your layout files.

When you get the error, is it only when you click the item in landscape mode or only in portrait mode or both? Does your TaskDetailsFragment activity use a layout file that could have discrepancies between landscape and portrait modes?


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();

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"
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-layout

How to check if a key exists in Json Object and get its value How to center the elements in ConstraintLayout Android - how to make a scrollable constraintlayout? Add ripple effect to my button with button background color? This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint Is it possible to put a ConstraintLayout inside a ScrollView? Differences between ConstraintLayout and RelativeLayout How to remove title bar from the android activity? How to have EditText with border in Android Lollipop Android: ScrollView vs NestedScrollView

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference