Error inflating class androidx fragment app fragmentcontainerview

I'm working on getting the Google Place API to appear within a CardView. The particular code I'm looking at is from GitHub, seems to be working for everyone else but I don't understand why it's th...

I’m working on getting the Google Place API to appear within a CardView.

The particular code I’m looking at is from GitHub, seems to be working for everyone else but I don’t understand why it’s throwing me an error.

This is the error I am getting:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.rizwanqureshi.kevstaxiscanterbury, PID: 6818
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rizwanqureshi.kevstaxiscanterbury/com.rizwanqureshi.kevstaxiscanterbury.CustomerMapsActivity}: android.view.InflateException: Binary XML file line #50 in com.rizwanqureshi.kevstaxiscanterbury:layout/activity_customer_maps: Binary XML file line #50 in com.rizwanqureshi.kevstaxiscanterbury:layout/activity_customer_maps: Error inflating class android.fragment.app.FragmentContainerView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        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:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: android.view.InflateException: Binary XML file line #50 in com.rizwanqureshi.kevstaxiscanterbury:layout/activity_customer_maps: Binary XML file line #50 in com.rizwanqureshi.kevstaxiscanterbury:layout/activity_customer_maps: Error inflating class android.fragment.app.FragmentContainerView
     Caused by: android.view.InflateException: Binary XML file line #50 in com.rizwanqureshi.kevstaxiscanterbury:layout/activity_customer_maps: Error inflating class android.fragment.app.FragmentContainerView
     Caused by: java.lang.ClassNotFoundException: android.fragment.app.FragmentContainerView
        at java.lang.Class.classForName(Native Method)
        at java.lang.Class.forName(Class.java:454)
        at android.view.LayoutInflater.createView(LayoutInflater.java:815)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1006)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1123)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1126)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1126)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:682)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
        at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:438)
        at android.app.Activity.setContentView(Activity.java:3324)
        at com.rizwanqureshi.kevstaxiscanterbury.CustomerMapsActivity.onCreate(CustomerMapsActivity.java:116)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        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:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "android.fragment.app.FragmentContainerView" on path: DexPathList[[zip file "/data/app/com.rizwanqureshi.kevstaxiscanterbury-Nkg-1mQCfbE8I1MoJKHQuA==/base.apk"],nativeLibraryDirectories=[/data/app/com.rizwanqureshi.kevstaxiscanterbury-Nkg-1mQCfbE8I1MoJKHQuA==/lib/x86, /system/lib, /system/product/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
            ... 32 more

The main takeaway is that there is an Error inflating class android.fragment.app.FragmentContainerView and that the issue is at line 50 of the XML.

This is the XML:

<FrameLayout
    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"
    tools:context=".CustomerLogin" >


    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/buttons">
            <Button
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:id="@+id/logout"
                android:text="logout"
                tools:ignore="ButtonStyle" />
            <Button
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:id="@+id/history"
                android:text="history"
                tools:ignore="ButtonStyle" />
            <Button
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:id="@+id/settings"
                android:text="Settings"
                tools:ignore="ButtonStyle" />
        </LinearLayout>

        <androidx.cardview.widget.CardView
            android:layout_below="@+id/buttons"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="20sp">



//***LINE 50 WHERE THE ERROR IS***



            <android.fragment.app.FragmentContainerView
                android:id="@+id/place_autocomplete_fragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:ignore="ExtraText">
                android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
            </android.fragment.app.FragmentContainerView>
        </androidx.cardview.widget.CardView>
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_gravity="bottom">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/driverInfo"
            android:layout_gravity="bottom"
            android:orientation="horizontal"
            android:background="@android:color/white"
            android:visibility="gone">
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:paddingLeft="40sp">
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:background="@android:color/white"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </LinearLayout>
    </LinearLayout>
</FrameLayout>

So I guess there is something wrong with the FragmentContainerView? But i’m not getting any errors in the code and nothing is coming up on Google.

I feel like maybe something is outdated rather than outright incorrect but I haven’t a clue.

Thanks for any input.

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

Dinithe Pieris's user avatar

asked Jun 21, 2011 at 11:58

tsync's user avatar

11

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.

Paul's user avatar

Paul

6707 silver badges19 bronze badges

answered Feb 6, 2012 at 22:21

Dandre Allison's user avatar

Dandre AllisonDandre Allison

5,9455 gold badges41 silver badges56 bronze badges

4

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

answered Feb 28, 2013 at 13:51

Grigori A.'s user avatar

Grigori A.Grigori A.

2,5881 gold badge20 silver badges19 bronze badges

8

Make sure your Activity extends FragmentActivity.

answered May 22, 2012 at 21:04

james's user avatar

jamesjames

26k19 gold badges98 silver badges112 bronze badges

3

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.

answered Jan 25, 2014 at 0:12

Matiss's user avatar

MatissMatiss

5,0092 gold badges26 silver badges27 bronze badges

3

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

answered Aug 2, 2011 at 17:42

Wilko's user avatar

WilkoWilko

2401 silver badge4 bronze badges

3

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.

answered Feb 24, 2016 at 18:13

Dhiraj Gupta's user avatar

Dhiraj GuptaDhiraj Gupta

9,2457 gold badges49 silver badges52 bronze badges

5

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;

answered Jan 31, 2012 at 17:01

hdemirchian's user avatar

2

Have you tried:

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

answered Jun 21, 2011 at 13:08

Blundell's user avatar

BlundellBlundell

74.5k30 gold badges208 silver badges232 bronze badges

1

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)

bhass1's user avatar

bhass1

3302 silver badges7 bronze badges

answered Oct 10, 2012 at 9:32

Lei's user avatar

LeiLei

6501 gold badge6 silver badges13 bronze badges

1

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. :)

Sergey Glotov's user avatar

answered Dec 28, 2011 at 7:07

Suryavel TR's user avatar

Suryavel TRSuryavel TR

3,4161 gold badge20 silver badges25 bronze badges

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.

answered May 7, 2012 at 19:03

mask's user avatar

maskmask

6,0843 gold badges22 silver badges23 bronze badges

0

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.

approxiblue's user avatar

approxiblue

6,89216 gold badges50 silver badges59 bronze badges

answered Aug 24, 2014 at 15:13

xMythicx's user avatar

xMythicxxMythicx

8271 gold badge11 silver badges27 bronze badges

0

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

answered Aug 3, 2014 at 10:39

Gil's user avatar

GilGil

5685 silver badges9 bronze badges

1

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?

answered Jun 21, 2011 at 13:19

Nathan Fig's user avatar

Nathan FigNathan Fig

14.8k9 gold badges42 silver badges57 bronze badges

3

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.

answered Aug 25, 2016 at 10:42

Shaheer Palollathil's user avatar

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

answered Feb 3, 2022 at 9:47

Fakhriddin Abdullaev's user avatar

1

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.

answered Apr 25, 2014 at 19:21

oddmeter's user avatar

oddmeteroddmeter

7547 silver badges16 bronze badges

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>

approxiblue's user avatar

approxiblue

6,89216 gold badges50 silver badges59 bronze badges

answered Jun 19, 2013 at 11:34

Khushboo's user avatar

KhushbooKhushboo

2,9952 gold badges22 silver badges23 bronze badges

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

answered Sep 4, 2018 at 15:34

Sahaj Rana's user avatar

Sahaj RanaSahaj Rana

1,9633 gold badges24 silver badges42 bronze badges

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.

JoshDM's user avatar

JoshDM

4,9137 gold badges44 silver badges72 bronze badges

answered Jun 11, 2013 at 22:43

Christian Bøge-Rasmussen's user avatar

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

answered Apr 5, 2016 at 10:51

Vaibhav Sharma's user avatar

Vaibhav SharmaVaibhav Sharma

2,2531 gold badge17 silver badges23 bronze badges

2

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

answered Nov 1, 2019 at 14:46

ghost deathrider's user avatar

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.

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered May 17, 2021 at 11:35

QuartZ's user avatar

QuartZQuartZ

1543 silver badges11 bronze badges

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.

answered May 2, 2013 at 9:37

Lucas de Vil's user avatar

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

answered Nov 12, 2013 at 8:54

DjP's user avatar

DjPDjP

4,4472 gold badges23 silver badges34 bronze badges

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

answered Jun 27, 2014 at 15:49

D Kurovskyi's user avatar

D KurovskyiD Kurovskyi

1,05110 silver badges22 bronze badges

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.

answered Jul 13, 2014 at 10:16

AdamVe's user avatar

AdamVeAdamVe

3,1362 gold badges17 silver badges12 bronze badges

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?

Siddharth's user avatar

Siddharth

9,28215 gold badges86 silver badges144 bronze badges

answered Feb 22, 2015 at 19:05

Ahmad Moussa's user avatar

Ahmad MoussaAhmad Moussa

1,28118 silver badges22 bronze badges

Make sure your Activity extends FragmentActivity or AppCompatActivity

answered May 3, 2016 at 6:06

Riyas PK's user avatar

Riyas PKRiyas PK

3,0571 gold badge22 silver badges29 bronze badges

1

I’m trying to transition from using a FrameLayout to using FragmentContainerView and from the tutorials I’ve seen, it should be pretty easy. However, when I run my app after making the change, I get

Error inflating class androidx.fragment.app.FragmentContainerView
Caused by: java.lang.ClassNotFoundException: androidx.fragment.app.FragmentContainerView

my layout file is pretty simple:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="@layout/app_bar_main">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

Do I need to add something into my build.gradle or something? Why can’t it find the class?

Answer

That’s in androidx.fragment 1.2.0 or higher:

implementation "androidx.fragment:fragment:1.2.0"

Attribution
Source : Link , Question Author : Randy , Answer Author : CommonsWare

Error Description:

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 we switch via the portrait and the landscape mode and when we use fragments. The 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>
click below button to copy the code. By — android tutorial — team
  • If we switch via landscape and portrait mode everything works fine. But when we click on the fragment and then switch to the other mode we get the error.
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

click below button to copy the code. By — android tutorial — team

Solution 1:

  • Make sure to use:
import android.support.v4.app.Fragment;
click below button to copy the code. By — android tutorial — team
  • And also make sure that the Activity that is using the fragment(s) extends FragmentActivity instead of the regular Activity to get the FragmentActivity class.
import android.support.v4.app.FragmentActivity;
click below button to copy the code. By — android tutorial — team

Solution 2:

  • 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;
}
click below button to copy the code. By — android tutorial — team

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

click below button to copy the code. By — android tutorial — team

Solution 3:

  • Make sure your Activity extends FragmentActivity.

Solution 4:

  • The solution for is the order of super.onCreate and setContentView within the FragmentActivity
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fc_activity_list_profiles);
click below button to copy the code. By — android tutorial — team

I updated navigation component to 2.3.2 version.

In the 2.3.1 version work normally

I was going through the documentation and I did not find anything about the error or about any update in the component

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.m.marketplace, PID: 16698
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.m.marketplace/com.m.marketplace.ui.MainActivity}: android.view.InflateException: Binary XML file line #11 in com.m.marketplace:layout/activity_main: Binary XML file line #11 in com.m.marketplace:layout/activity_main: Error inflating class androidx.fragment.app.FragmentContainerView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3311)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3460)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        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:2047)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:224)
        at android.app.ActivityThread.main(ActivityThread.java:7590)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: android.view.InflateException: Binary XML file line #11 in com.m.marketplace:layout/activity_main: Binary XML file line #11 in com.m.marketplace:layout/activity_main: Error inflating class androidx.fragment.app.FragmentContainerView
     Caused by: android.view.InflateException: Binary XML file line #11 in com.m.marketplace:layout/activity_main: Error inflating class androidx.fragment.app.FragmentContainerView
     Caused by: java.lang.IllegalArgumentException
        at androidx.lifecycle.LifecycleRegistry.downEvent(LifecycleRegistry.java:263)
        at androidx.lifecycle.LifecycleRegistry.backwardPass(LifecycleRegistry.java:314)
        at androidx.lifecycle.LifecycleRegistry.sync(LifecycleRegistry.java:334)
        at androidx.lifecycle.LifecycleRegistry.moveToState(LifecycleRegistry.java:145)
        at androidx.lifecycle.LifecycleRegistry.setCurrentState(LifecycleRegistry.java:118)
        at androidx.navigation.NavBackStackEntry.updateState(NavBackStackEntry.java:150)
        at androidx.navigation.NavBackStackEntry.setMaxLifecycle(NavBackStackEntry.java:130)
        at androidx.navigation.NavController.popBackStackInternal(NavController.java:325)
        at androidx.navigation.NavController.navigate(NavController.java:1050)
        at androidx.navigation.NavController.navigate(NavController.java:942)
        at com.m.marketplace.utils.ktx.NavControllerKt.navigateSafe(NavController.kt:17)
        at com.m.marketplace.utils.ktx.NavControllerKt.navigateSafe$default(NavController.kt:13)
        at com.m.marketplace.utils.ktx.FragmentKt.navigate(Fragment.kt:15)
        at com.m.marketplace.ui.login.view.PreviousLoginDialog.goToHome(PreviousLoginDialog.kt:119)
        at com.m.marketplace.ui.login.view.PreviousLoginDialog.access$goToHome(PreviousLoginDialog.kt:28)
        at com.m.marketplace.ui.login.view.PreviousLoginDialog$firstInit$1.invoke(PreviousLoginDialog.kt:111)
        at com.m.marketplace.ui.login.view.PreviousLoginDialog$firstInit$1.invoke(PreviousLoginDialog.kt:28)
        at com.m.marketplace.ui.login.view.PreviousLoginDialog.onCreate(PreviousLoginDialog.kt:44)
        at androidx.fragment.app.Fragment.performCreate(Fragment.java:2684)
        at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:280)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1175)
        at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
    E/AndroidRuntime:     at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2629)
        at androidx.fragment.app.FragmentManager.dispatchCreate(FragmentManager.java:2571)
        at androidx.fragment.app.Fragment.onCreate(Fragment.java:1685)
        at androidx.navigation.fragment.NavHostFragment.onCreate(NavHostFragment.java:264)
        at androidx.fragment.app.Fragment.performCreate(Fragment.java:2684)
        at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:280)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1175)
        at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
        at androidx.fragment.app.FragmentManager.execSingleAction(FragmentManager.java:1818)
        at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:303)
        at androidx.fragment.app.FragmentContainerView.<init>(FragmentContainerView.java:166)
        at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:51)
        at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
        at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:356)
        at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:335)
        at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1073)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1001)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1127)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:686)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:538)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170)
        at com.m.marketplace.ui.MainActivity.onCreate(MainActivity.kt:50)
        at android.app.Activity.performCreate(Activity.java:7893)
        at android.app.Activity.performCreate(Activity.java:7880)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3286)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3460)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        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:2047)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:224)
        at android.app.ActivityThread.main(ActivityThread.java:7590)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

4 Answers

I was facing the same problem and I figured out that Android studio is not adding name tags in navigation graph. So, adding name tag in navigation graph xml worked for me.

In nav_graph.xml

<fragment
    android:id="@+id/loginFragment"
    android:name="com.example.MyApp.fragments.LoginFragment"
    android:label="fragment_login"
    tools:layout="@layout/fragment_login">

Or if you are not sure then switch to the design and in attributes tab on right side select the class name from drop-down list

Name Tag in Design View

Same issue here with navigation component 2.3.2 version.

In the 2.3.1 version works normally

If you’re using Jetpack Compose change MainActivity extends to AppCompatActivity instead of CompatActivity

First make sure you have added ID to your nav graph and fragment container view. Also check fragment (declared asstart destination) does not have any instantiation issue.

[Solved-4 Solutions] Error inflating class fragment

Error Description:

We get the Error

Unable to start activity ComponentInfo: android.view.InflateException: Binary XML file line #11: Error inflating class fragment

  • when we switch via the portrait and the landscape mode and when we use fragments. The xml is:
click below button to copy the code. By — android tutorial — team
  • If we switch via landscape and portrait mode everything works fine. But when we click on the fragment and then switch to the other mode we get the error.
click below button to copy the code. By — android tutorial — team

Solution 1:

click below button to copy the code. By — android tutorial — team
  • And also make sure that the Activity that is using the fragment(s) extends FragmentActivity instead of the regular Activity to get the FragmentActivity class.
click below button to copy the code. By — android tutorial — team

Solution 2:

  • 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:
click below button to copy the code. By — android tutorial — team

Pattern #1

click below button to copy the code. By — android tutorial — team

Solution 3:

  • Make sure your Activity extends FragmentActivity.

Solution 4:

  • The solution for is the order of super.onCreate and setContentView within the FragmentActivity
click below button to copy the code. By — android tutorial — team

Related Searches to Error inflating class fragment

World’s No 1 Animated self learning Website with Informative tutorials explaining the code and the choices behind it all.

Источник

Android error inflating class fragmentcontainerview

i am using above layout and i am getting same error (Layout inflation error).Please let me know where i am wrong.

There are other reasons for getting such an error- not just in the misspelling of a widget name or tool. I got that error when I used a drawable file (containing a color I created using xml code) as my textcolor. It appears errors generated can cover a truckload of reasons and not just one reason.

im also getting this error

The mobile version works great, but the tablet version gives the above error. tablet layout:

EDIT, something went wrong and the post has been posted 3 times

Repeated, sorry about that

I was custom styling the buttons by using custom xml file inside the drawable folder. I was getting the following error: Binary XML file line #1: Error inflating class button

This issues almost made me break my head.

But I resolved it. I believe it happens because either the XML is not properly formatted (missing OR spelling mistakes) or incorrect xmlns:android URL.

Also make sure please that in .axml file, when you specify the xml as background or whatever, use this format: android:background=»@drawable/yourxmlfilenamewithoutfiletype»_

Thanks and Cheers!

In my case this exception was caused by the package name. Just in case someone else has the same issue you can find below what I found at the very bottom of the following link:

It is very important to remember that when adding a fragment to a layout file, that Android expects the package name to be lower-case. If the package name is upper-case then an Android.Views.InflateException will be thrown.

In my case, the problem was caused by the fact that I failed to return the correct value. I believe the line with the return below was auto generated for me, and as a result I didn’t look at it too closely and didn’t notice that it was returning the wrong thing.

All I had to do was return the view:

I hope this helps someone.

I’ve got same issue from Fabric/Crashlytics.

Fatal Exception: java.lang.RuntimeException Unable to start activity ComponentInfo: android.view.InflateException: Binary XML file line #1: Binary XML file line #1: Error inflating class

my axml file is following

** using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;

using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Text;

using RoadRunner.Shared; using RoadRunner.Shared.Classes;

I’ve wasted many time with this issue but couldn’t find any solution in anywhere.

I’ve attached above .AXML and .cs files.

I’m new to Xamarin, I got the same error, I was trying to make a Maps fragment in the app, can someone help me?

The way i fixed this error was clean and rebuild. And the rebuild might take longer than it should, try it out, worked for me

Sorry posted at wrong window

Hi! I have the same problem -> Android.Views.InflateException: Binary XML file line #1: Error inflating class GrumsonLed

I don’t know what is wrong! Can someone please help me!

Источник

Неочевидное про Fragment API. Часть 2. (Не) создаем инстанс

Всем привет! Меня зовут Максим Бредихин, я Android-разработчик в Тинькофф. А это — вторая статья серии об интересных моментах из Fragment API, о которых вы, возможно, не знали.

Часть 2. (Не) создаем инстанс (вы находитесь здесь)

Готовьте вкусности, сегодня я расскажу, как (не) создавать новые инстансы фрагментов.

Fragment в XML

Для работы с фрагментами не обязательно использовать FragmentManager напрямую. Если у нас есть стартовый фрагмент, достаточно указать его в XML через атрибут name у контейнера.

Дополнительно ничего делать не нужно, но под капотом без FragmentManager не обошлось. Вся магия происходит в четыре этапа:

FragmentContainerView в конструкторе берет FragmentManager из родительского контекста. Если контейнер фрагмента находится в разметке Activity, будет использован supportFragmentManager , а если в разметке фрагмента — childFragmentManager .

С помощью FragmentFactory создается инстанс фрагмента, указанного в поле android:name .

Сразу после этого и до начала транзакции у фрагмента вызывается коллбэк Fragment.onInflate(Context, AttributeSet, Bundle?) .

Стоит разобраться с onInflate() . Он вызывается до начала транзакции и, следовательно, дергается до всех коллбэков жизненного цикла.

Жизненный цикл

Первое и главное условие для вызова этого метода: фрагмент должен создаваться через XML. А дальше у нас две дороги:

если мы — модные, молодежные и современные разработчики, которые слушают Google и используют в качестве контейнера FragmentContainerView , этот метод будет вызван только один раз при первом создании инстанса фрагмента;

если мы предпочитаем старые подходы и используем в разметке, метод onInflate() будет полноценным методом жизненного цикла, который вызывается перед onAttach() . Несмотря на это, я не пропагандирую такой способ.

В остальных случаях метод не вызывается никогда. Его основное предназначение — достать аргументы из XML. Для этого нужно определить свои атрибуты для аргументов в ресурсах приложения.

Создаем файл attrs.xml, прописываем нужные аргументы и указываем их в разметке.

На следующем шаге достаем аргументы из attrs в onInflate() .

Отойдем от аргументов и вспомним, что в транзакции при желании можно присвоить фрагменту tag. То же самое можно сделать через XML. Для этого достаточно указать android:tag у контейнера.

Важно! Создать фрагмент из XML мы можем, только указав ID у контейнера, иначе упадем с IllegalStateException . Это нужно для сохранения состояния при пересоздании View.

На момент Fragments: 1.5.0 с таким фрагментом можно совершать любые транзакции, доступные для обычных фрагментов. Главное — выбрать нужный FragmentManager и достать фрагмент через ID контейнера или указанный в XML тег.

FragmentFactory

В генах Android-разработчика прописано, что мы обязаны создавать фрагменты с пустым конструктором, чтобы система могла их самостоятельно пересоздать. Однако в версии Fragments 1.1.0 у нас появилась возможность контролировать создание инстансов фрагментов, в том числе добавлять любые параметры и зависимости в конструктор.

Для этого достаточно подменить стандартную реализацию FragmentFactory на свою, где мы сами себе цари и боги.

Главное — успеть заменить реализацию до того, как она понадобится FragmentManager’у, то есть до первой транзакции и восстановления состояния после пересоздания. Чем раньше мы заменим негодную реализацию, тем лучше.

Для Activity лучшим сценарием будет замена:

У фрагментов доступ к своему FragmentManager’у появляется не сразу. Поэтому подмену мы можем совершить только между onAttach() и onCreate() включительно, иначе увидим страшный красный текст в логах после запуска. Но важно помнить, что parentFragmentManager — это FragmentManager, через который совершили коммит. Следовательно, если в нем ранее заменили FragmentFactory, делать это во второй раз не нужно.

Теперь разберемся, как нам реализовать свою фабрику. Создаем класс, наследуемся от FragmentFactory и переопределяем метод instantiate() .

На вход получаем classLoader , который можно использовать для создания Class , и className — полное имя нужного фрагмента. Исходя из имени определяем, какой фрагмент нам нужно создать, и возвращаем его. Если мы не знаем такого фрагмента, передаем управление родительской реализации.

Примерно так все выглядит super.instantiate() под капотом FragmentFactory:

Транзакции без создания Fragment

Кто-то может сказать: «FragmentFactory — штука классная, но для транзакций нам все равно нужны конкретные инстансы, так что пойду-ка я добавлю в свой фрагмент companion object». И он будет прав, но только если сидит на фрагментах до версии 1.2.0.

В этой версии нас избавили от необходимости создавать инстанс фрагмента в транзакции вручную, добавив дополнительные перегрузки методов FragmentTransaction.add() :

Аналогичные методы добавили и для FragmentTransaction.replace() . Теперь мы можем сделать так:

Или использовать fragment-ktx и расширение с reified-дженериком, которое я упоминал в первой части цикла.

Что еще круче, теперь мы можем передать аргументы сразу во время транзакции:

Или с использованием fragment-ktx:

Во фрагменте нам останется только достать их как обычные аргументы:

LayoutId в конструкторе

Вспомним, как мы учились работать с фрагментами. Создаем класс, создаем файл разметки и «надуваем» его в onCreateView() :

Мы сотни раз набирали эти родные сердцу строки, но в версии Fragments 1.1.0 ребята из Google решили, что больше не будут это терпеть. Они добавили фрагментам второй конструктор, принимающий на вход @LayoutRes , благодаря которому больше не нужно переопределять onCreateView() .

А под капотом работает тот же самый бойлерплейт:

Чем меньше кода нам придется писать, тем лучше. Поэтому давайте не будем писать шаблонный код, если этого можно избежать.

Если вдруг вы до этого инициализировали View в onCreateView() , правильнее использовать специальный коллбэк onViewCreated() , вызываемый сразу после onCreateView() .

Вместо заключения

Подошла к концу вторая часть цикла «Неочевидного о фрагментах». В этой статье мы разобрались с созданием фрагментов в XML, добавили зависимости в конструктор через FragmentFactory, узнали, что создавать фрагменты в транзакциях не обязательно, и избавились от небольшого кусочка бойлерплейта в нашем коде.

Теперь вы сможете использовать фрагменты без companion object для создания и сделать свой код немного чище.

В следующей статье мы посмотрим на новые и не очень фишки навигации между фрагментами. До встречи!

Источник

  • Remove From My Forums
  • Question

  • User1763 posted

    Hi,

    My code is

    Main.axml:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <Button
            android:id="@+id/MyButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/Hello" />
        <fragement
            android:name="test.fragement.example.Fragment1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout> 
    

    and Activity1.cs

    public class Activity1 : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);          
        }
    }
    

    and Fragment1.cs

    namespace test.fragement.example
    {
        public class Fragment1 : Fragment
        {
            public override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
            }
            public override View OnCreateView(LayoutInflater inflater, ViewGroup grp, Bundle bundle)
            {
                base.OnCreateView(inflater, grp, bundle);
                View vw = inflater.Inflate(Resource.Layout.frag1, grp, true);
                return vw;
            }
        }
    }
    

    This code is throwing an error for me. Stack trace

    Android.Views.InflateException: Binary XML file line #1: Error inflating class fragement
      at Android.Runtime.JNIEnv.CallNonvirtualVoidMethod (intptr,intptr,intptr,Android.Runtime.JValue[]) [0x00024] in /Users/builder/data/lanes/monodroid-mac-monodroid-4.4-series/6418373f/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:616
      at Android.App.Activity.SetContentView (int) [0x0006b] in /Users/builder/data/lanes/monodroid-mac-monodroid-4.4-series/6418373f/source/monodroid/src/Mono.Android/platforms/android-10/src/generated/Android.App.Activity.cs:3119
      at test.fragement.example.Activity1.OnCreate (Android.OS.Bundle) [0x00009] in c:Monotest.fragement.exampletest.fragement.exampleActivity1.cs:22
      at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (intptr,intptr,intptr) [0x00010] in /Users/builder/data/lanes/monodroid-mac-monodroid-4.4-series/6418373f/source/monodroid/src/Mono.Android/platforms/android-10/src/generated/Android.App.Activity.cs:1490
      at (wrapper dynamic-method) object.4b6fec41-0b84-4cbb-85e3-f821d04add6e (intptr,intptr,intptr) <IL 0x00017, 0x00043>
      --- End of managed exception stack trace ---
      android.view.InflateException: Binary XML file line #1: Error inflating class fragement
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:581)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
        at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
        at android.app.Activity.setContentView(Activity.java:1657)
        at test.fragement.example.Activity1.n_onCreate(Native Method)
        at test.fragement.example.Activity1.onCreate(Activity1.java:28)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
        at android.app.ActivityThread.access$1500(ActivityThread.java:117)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:123)
        at android.app.ActivityThread.main(ActivityThread.java:3683)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:507)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
        at dalvik.system.NativeStart.main(Native Method)
      Caused by: java.lang.ClassNotFoundException: android.view.fragement in loader dalvik.system.PathClassLoader[/data/app/test.fragement.example-1.apk]
        at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
        at android.view.LayoutInflater.createView(LayoutInflater.java:471)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:549)
        at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:66)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568)
        ... 21 more
    

    How to solve this ?

Answers

  • User7668 posted

    What a numpty. I have put the namespace in the path for the classname now and of course it works. Sorry for wasting everyone’s time

    • Marked as answer by

      Thursday, June 3, 2021 12:00 AM

Add Answer
|
View In TPC Matrix

Technical Problem Cluster First Answered On
June 9, 2020

Popularity
9/10

Helpfulness
4/10


Contributions From The Grepper Developer Community

Contents

Code Examples

  • Error inflating class androidx.fragment.app.FragmentContainerView
  • Related Problems

  • error inflating class androidx.fragment.app.fragmentcontainerview
  • layout/activity_main: Error inflating class fragment
  • error inflating class fragment navhostfragment
  • caused by: androidx.fragment.app.fragment$instantiationexception: unable to instantiate fragment bsmconnekt2.ui.home.homefragment: make sure class name exists at androidx.fragment.app.fragmentfactory.loadfragmentclass
  • TPC Matrix View Full Screen

    Error inflating class androidx.fragment.app.FragmentContainerView

    Comment

    1


    Popularity

    9/10 Helpfulness
    4/10
    Language
    whatever

    Source: stackoverflow.com

    Tags: whatever

    Precious Pheasant

    Contributed on Jun 09 2020

    Precious Pheasant

    24 Answers  Avg Quality 7/10


    Понравилась статья? Поделить с друзьями:
  • Error indirection requires pointer operand int invalid
  • Error indexing must appear last in an index expression
  • Error index was outside the bounds of the array
  • Error index row requires bytes maximum size is 8191
  • Error incorrect verification number entered