android.view.InflateException: Binary XML file: Error inflating class fragment
Asked Answered
L

42

206

I have a very frustrating error that I cannot explain. I created an Android application that uses Android AppCompat to make it compatible with older versions. Here is my main activity layout file:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- As the main content view, the view below consumes the entire
         space available using match_parent in both dimensions. -->
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- android:layout_gravity="start" tells DrawerLayout to treat
         this as a sliding drawer on the left side for left-to-right
         languages and on the right side for right-to-left languages.
         If you're not building against API 17 or higher, use
         android:layout_gravity="left" instead. -->

    <!-- The drawer is given a fixed width in dp and extends the full height of
         the container. -->
    <fragment android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:name="com.fragment.NavigationDrawerFragment" />

</android.support.v4.widget.DrawerLayout>

And here is main code of my activity :

public class MainActivity extends ActionBarActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
   }
}

The main problem here is : above code run smoothly on almost devices (stimulated device, or some real devices). But when I run it on Samsung S3. It notices this error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{view.MainActivity}: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2081)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2106)
            at android.app.ActivityThread.access$700(ActivityThread.java:134)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1217)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4856)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:316)
            at android.app.Activity.setContentView(Activity.java:1901)
            at android.support.v7.app.ActionBarActivity.superSetContentView(ActionBarActivity.java:208)
            at android.support.v7.app.ActionBarActivityDelegateICS.setContentView(ActionBarActivityDelegateICS.java:111)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:76)

Please tell me how to fix error, thanks :)

Land answered 9/11, 2013 at 10:26 Comment(6)
In this line you are getting exception check whether the class name and package name are correct or not..android:name="com.hqt.hac.view.fragment.NavigationDrawerFragment"Bangweulu
i have checked and this class is true. i can compile and run on some devices but not samsung s3. i think some strange problems here :(Land
you are right if it is executing on some device and not on s3 it's a strange problem..my advice is once try to use sherlacFragment chek once..Bangweulu
I already solved issue here: https://mcmap.net/q/129202/-add-custom-view-as-a-view-of-xml-layout .Docent
For those who are trying to diagnose the cause of this error: The anecdotal fixes here are a red herring. There is a prior exception occurring during inflation of the fragment that isn't showing up in the stack trace. It could be anything. To fix the problem, you have to find out what the prior exception is. To do that, see my answer or @DaveHubbard's.Brig
My image files were in the "drawable-v24" folder. I copied them to the "drawable" folder too. Problem solved. i got this solution from github.com/chrisjenx/Calligraphy/issues/417Fractocumulus
L
157

After long time for debugging, I have fixed this problem. (Although I still cannot explain why). That I change property android:name to class. (although on Android Document, they say those properties are same, but it works !!!)

So, it should change from :

 android:name="com.fragment.NavigationDrawerFragment"

to

class = "com.fragment.NavigationDrawerFragment"

So, new layout should be :

<!-- As the main content view, the view below consumes the entire
     space available using match_parent in both dimensions. -->
<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<!-- android:layout_gravity="start" tells DrawerLayout to treat
     this as a sliding drawer on the left side for left-to-right
     languages and on the right side for right-to-left languages.
     If you're not building against API 17 or higher, use
     android:layout_gravity="left" instead. -->

<!-- The drawer is given a fixed width in dp and extends the full height of
     the container. -->
<fragment android:id="@+id/navigation_drawer"
    android:layout_width="@dimen/navigation_drawer_width"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    class = "com.fragment.NavigationDrawerFragment" />

Hope this help :)

Land answered 13/11, 2013 at 11:16 Comment(5)
I ran into this issue when trying to follow the official Android tutorial. Your fix (changing android:id to class) worked for me. I also got a Lint warning to change Fragment to fragment, which I did.Dupont
@DownVoter: this error is confuse. And I luckily find the way to fix. I'm really sorry if my post cannot fix your error because I also cannot explain why. But I think it should not receive a down vote. :)Land
I wonder if you got this crash reliably without changing from name to class, I have had a few users report this crash but cannot repro it myself!Basketry
Doesn't work for me. I am so tired. 2h of dev and cannot find why it doesn't work (Binary xml file line... errror inflating class fragment). Any idea ?Boyish
Outdated ! Any idea with the "androidx.fragment.app.FragmentContainerView" ?Educator
B
74

TL/DR: An exception occurred during the creation of a fragment referenced from a higher-level layout XML. This exception caused the higher-level layout inflation to fail, but the initial exception was not reported; only the higher-level inflation failure shows up in the stack trace. To find the root cause, you have to catch and log the initial exception.


The initial cause of the error could be a wide variety of things, which is why there are so many different answers here as to what fixed the problem for each person. For some, it had to do with the id, class, or name attributes. For others it was due to a permissions issue or a build setting. For me, those didn't fix the problem; instead there was a drawable resource that existed only in drawable-ldrtl-xhdpi, instead of in an applicable place like drawable.

But those are just details. The big-picture problem is that the error message that shows up in logcat doesn't describe the exception that started it all. When a higher-level layout XML references a fragment, the fragment's onCreateView() is called. When an exception occurs in a fragment's onCreateView() (for example while inflating the fragment's layout XML), it causes the inflation of the higher-level layout XML to fail. This higher-level inflation failure is what gets reported as an exception in the error logs. But the initial exception doesn't seem to travel up the chain well enough to be reported.

Given that situation, the question is how to expose the initial exception, when it doesn't show up in the error log.

The solution is pretty straightforward: Put a try/catch block around the contents of the fragment's onCreateView(), and in the catch clause, log the exception:

public View onCreateView(LayoutInflater inflater, ViewGroup contnr, Bundle savedInstSt) {
    try {
        mContentView = inflater.inflate(R.layout.device_detail_frag, null);
        // ... rest of body of onCreateView() ...
    } catch (Exception e) {
        Log.e(TAG, "onCreateView", e);
        throw e;
    }
}

It may not be obvious which fragment class's onCreateView() to do this to, in which case, do it to each fragment class that's used in the layout that caused the problem. For example, in the OP's case, the app's code where the exception occurred was

at android.app.Activity.setContentView(Activity.java:1901)

which is

   setContentView(R.layout.activity_main);

So you need to catch exceptions in the onCreateView() of any fragments referenced in layout activity_main.

In my case, the root cause exception turned out to be

Caused by: android.content.res.Resources$NotFoundException: Resource
   "com.example.myapp:drawable/details_view" (7f02006f)  is not a
   Drawable (color or path): TypedValue{t=0x1/d=0x7f02006f a=-1
   r=0x7f02006f}

This exception didn't show up in the error log until I caught it in onCreateView() and logged it explicitly. Once it was logged, the problem was easy enough to diagnose and fix (details_view.xml existed only under the ldrtl-xhdpi folder, for some reason). The key was catching the exception that was the root of the problem, and exposing it.

It doesn't hurt to do this as a boilerplate in all your fragments' onCreateView() methods. If there is an uncaught exception in there, it will crash the activity regardless. The only difference is that if you catch and log the exception in onCreateView(), you won't be in the dark as to why it happened.

P.S. I just realized this answer is related to @DaveHubbard's, but uses a different approach for finding the root cause (logging vs. debugger).

Brig answered 23/5, 2017 at 19:5 Comment(2)
For me, I solved my issue by setting the id of the inner fragment to be the same id as the one used to describe the inner fragment from the outer fragment. In other words, view.findViewById(R.id.blah) and then doing a Ctrl+Click on the "blah" should return multiple results for possible fragments.Nadabus
Better solution than most of the answers. All other solutions mostly won't work on modern Android Studio.Flong
V
37

I couldn't solve my problem using provided answers. Finally I changed this:

<fragment
android:id="@+id/fragment_food_image_gallery"
android:name="ir.smartrestaurant.ui.fragment.ImageGalleryFragment"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout="@layout/fragment_image_gallery"
tools:layout="@layout/fragment_image_gallery" />

to this :

<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="200dp" />

,

private void showGallery() {
    ImageGalleryFragment fragment = new ImageGalleryFragment()
    getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment)
                .commit();
    }

and it works.
If you are using it inside fragment, use getChildFragmentManager instead of getSupportFragmentManager.

Vouge answered 16/2, 2016 at 15:18 Comment(0)
S
23

I had the same problem, issue, tried all the answers in this thread to no avail. My solution was, I hadn't added an ID in the Activity XML. I didn't think it would matter, but it did.

So in the Activity XML I had:

<fragment
    android:name="com.covle.hellocarson.SomeFragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

But should've had:

<fragment
    android:id="@+id/some_fragment"
    android:name="com.covle.hellocarson.SomeFragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

If someone would be happy to comment on why this is, I'm all ears, to other, I hope this helps.

Saloma answered 4/8, 2015 at 10:54 Comment(2)
Thanks, this worked for me. I had been omitting an id for months, but after some layout changes suddenly I began having this crash. Android is weird.Csch
You answer works for me. I just wonder why I suppose to put id attribute when I am not using it anywhere. Can you explain to me?Barren
A
12

It might not be needed for you anymore, but if further readers find it helpful. I have exact same android.view.InflateException:...Error inflating class fragment. I had all right libraries included. Solved by adding one more user permission in the AndroidManifest.xml file i.e. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Btw I was running Android Studio 0.8.9 on Ubuntu 12.04.

Arsenic answered 9/10, 2014 at 12:0 Comment(1)
Worked for me! Thanks a lot!Iceblink
B
12

I have the same problem because I did not implement the listener. See the following code with /*Add This!*/.

public class SomeActivity extends AppCompatActivity
        implements BlankFragment.OnFragmentInteractionListener /*Add this!*/ 
{
    @Override                                                  /*Add This!*/
    public void onFragmentInteraction(Uri uri){                /*Add This!*/
    }                                                          /*Add This!*/
}

FYI, my fragment class is something like the following:

public class SomeFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }
}

Edit:

I also notice this same error message under another circumstances when there is an exception in the onCreate function of the Fragment. I have something as the following:

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

    int ID = getArguments().getInt("val");

    return rootView;
} 

Because I reuse this fragment, I total forget to set arguments. Then the result of getArguments() is null. Obviously, I get a null pointer exception here. I will suggest you keep an eye on mistakes like this as well.

Broomrape answered 22/8, 2015 at 15:29 Comment(1)
Thanks! This helped a lot!Pigpen
D
8

Is your NavigationDrawerFragment extending the android.support.v4.app.Fragment? In other words, are you importing the correct package?

import android.support.v4.app.Fragment;
Dippy answered 9/11, 2013 at 10:40 Comment(0)
B
6

I also had this issue. I solved it by replacing the import in MainActivity and NavigationDrawerFragment

From

import android.app.Activity;
import android.app.ActionBar;

To

import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;

I updated MainActivity to extends ActionBarActivity instead of Activity

public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks

Also use ActionBar actionBar = getSupportActionBar(); to get the ActionBar

And I updated the following function in NavigationDrawerFragment

private ActionBar getActionBar()
{
    return ((ActionBarActivity)getActivity()).getSupportActionBar();
}
Bespoke answered 4/11, 2014 at 15:17 Comment(1)
I think this is the right answer. But i used AppCompatActivity instead of ActionBarActivity (not deprecated) and also do not remove import android.app.ActionBar (as onAttach method use it)Spencer
E
6

I have had similar problems on and off. The error message often provides very little detail, regardless of actual cause. But I found a way to get more useful info. It turns out that the internal android class 'LayoutInflater.java' (in android.view package) has an 'inflate' method that re-throws an exception, but does not pick up the details, so you lose info on the cause.

I used AndroidStudio, and set a breakpoint at LayoutInflator line 539 (in the version I'm working in), which is the first line of the catch block for a generic exception in that 'inflate' method:

        } catch (Exception e) {
            InflateException ex = new InflateException(
                    parser.getPositionDescription()
                            + ": " + e.getMessage());
            ex.initCause(e);
            throw ex;

If you look at 'e' in the debugger, you will see a 'cause' field. It can be very helpful in giving you a hint about what really occurred. This is how, for example, I found that the parent of an included fragment must have an id, even if not used in your code. Or that a TextView had an issue with a dimension.

Exanimate answered 18/10, 2016 at 16:0 Comment(0)
U
6

i faced this problem and solved it by using following codes. I was beginning fragment transaction by using childfragment manager.

layout:

                  <fragment
                    class="com.google.android.youtube.player.YouTubePlayerSupportFragment"
                    android:id="@+id/youtube_fragment"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>

this is how i began fragment transaction:

   youTubePlayerFragment = (YouTubePlayerSupportFragment) getChildFragmentManager().findFragmentById(R.id.youtube_fragment);

the following codes explains how i removed the fragment which added by using childfragmentmanger.

@Override
    public void onDestroyView() {
        super.onDestroyView();

        youTubePlayerFragment = (YouTubePlayerSupportFragment) getChildFragmentManager().findFragmentById(R.id.youtube_fragment);

        if (youTubePlayerFragment != null)
        {
            getChildFragmentManager().beginTransaction().remove(youTubePlayerFragment).commitAllowingStateLoss();
        }

        youTubePlayer = null;
    }
Unsteel answered 8/12, 2016 at 9:13 Comment(2)
TY Ali .You saved my day !Copro
Works fine. Thank you!Nutritive
P
3

Just in case someone needs this. Assumptions: Device phone hooked up to USB cable and your IDE reading to launch the app. Go to the command prompt to determine issue: enter adb logcat

Then launch your app from IDE. You will an exception.

In my case: I was deploying an Android app of Version 2.3 to a mobile device that did not support the widget "Space"

Pentagrid answered 10/3, 2015 at 18:51 Comment(0)
S
3

This problem arises when you have a custom class that extends a different class (in this case a view) and does not import all the constructors required by the class.

For eg : public class CustomTextView extends TextView{}

This class would have 4 constructors and if you miss out on any one it would crash. For the matter of fact I missed out the last one which was used by Lollipop added that constructor and worked fine.

Snappy answered 15/3, 2016 at 7:52 Comment(0)
H
3

Add this name field in navigation

android:name="androidx.navigation.fragment.NavHostFragment"

   <fragment
             android:id="@+id/container"
             android:layout_width="match_parent"
             android:layout_height="0dp"
             android:name="androidx.navigation.fragment.NavHostFragment"
             app:navGraph="@navigation/navigation"
             app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
             app:layout_constraintTop_toTopOf="parent">
Hui answered 15/11, 2019 at 5:14 Comment(0)
N
2

we must also need to add following in build.gradle(app)

compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'

whenever we are using new layouts or new design features. hope this helps you.

Names answered 24/6, 2016 at 5:52 Comment(0)
I
2

As mentioned in a previous post,
rename

android:name="com.fragment.NavigationDrawerFragment"

to

class = "com.fragment.NavigationDrawerFragment"

Still, it did not work for me. I then just used the Class Name without the com.fragment part and voila it worked. So change it finally to

class = "NavigationDrawerFragment"
Inverter answered 6/1, 2017 at 22:44 Comment(0)
N
2

After none of the answers here helped me, I opted to run app in debug mode moving across every line of onCreateView in my fragment (NavigationDrawerFragment in your case). And noticed that fragment was having difficulty with inflating because of a NullPointerException. E.g.

mySeekBar = (SeekBar) getActivity().findViewById(R.id.mySeekBar);
mySeekBar.setOnSeekBarChangeListener(this);

Here mySeekBar was set to null (because I had missed adding the control in appropriate layout) and the next line got into NPE which came out as InflateException. Also, as suggested above, rename android:name to class.

This issue can arise for various reasons mentioned above. I would recommend line-by-line debug flow to know what is wrong.

Nanny answered 24/2, 2017 at 7:19 Comment(1)
And was this error occurring in a fragment's onCreateView() method?Brig
K
2

After long time of tries, this is how I solved the problem after none of the above answers could.

  1. Extend AppCompatActivity for your Main activity instead of Activity.
  2. Add android:theme="@style/Theme.AppCompat.Light" to your <Activity..../> in the AndroidManifest.xml
  3. In your NavigationDrawerFragment Class, change your ActionBar instances to

    ActionBar mActionBar=((AppCompatActivity)getActivity()).getSupportActionBar();
    

EDIT

It should be a consistency between the Activity and Layout. If the Layout has one of the AppCompat Theme such like Theme.AppCompat.Light, your Activity should extends AppCompatActivity.

I wanted to have the burger icon and a Navigation Drawer that looks like the Android Gmail App, but I ended up with an ugly Navigation Drawer. All that because all my Classes extends Activity instead of AppCompatActivity.

I re-factored the entire project to extend AppCompatActivity, then Right-Click on the Layout Folder, chose new -> Activity then Navigation Drawer Activity and Boom, everything is done for me!

Knotgrass answered 18/2, 2018 at 19:3 Comment(0)
D
2
android.view.InflateException: Binary XML file line #16: Error inflating class com.google.android.material.bottomappbar.BottomAppBar

The view can be anything that is failing to get inflated, this kind of error comes when there is a clash in resolving the class names or name attribute of a view referred in the XML file.

When I get the same error I just got everything clean and safe in UI-XML file, the view I was using,

   <com.google.android.material.bottomappbar.BottomAppBar
    android:id="@+id/bottomAppBar"
    style="@style/Widget.MaterialComponents.BottomAppBar.Colored"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    app:hideOnScroll="true"
    app:menu="@menu/bottom_app_bar"
    app:navigationIcon="@drawable/ic__menu_24"/>

I was using a style attribute which was referring the Material components property. But my styles.xml had...

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
....
</style>

Where the class resolving was facing the conflict. My view attributes referred a property that was not defined in my app theme. The right parent theme from material components helped me. So I changed the parent attribute to...

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
...
</style>

Which resolved the issue.

Distance answered 22/6, 2020 at 14:20 Comment(0)
H
2

I don`t know what happened, but Changing Fragment to FrameLayout solved my problem after many hours of struggle.

<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Hudspeth answered 5/4, 2021 at 12:7 Comment(0)
W
1

For some of you that still haven't found a solution for this, in my case it was happening because I had an OOM (Out of Memory) issue. This can happen when you have for example a memory leak in your app when using it for a long time. In my stack trace, this was the main reason.

Whorled answered 8/12, 2015 at 15:58 Comment(0)
D
1

I don't know if this will help.

I had this problem with a TextView I had in the layout I was trying to inflate (android.view.InflateException: Binary XML file line #45: Error inflating class TextView).

I had set the following XML attribute android:textSize="?android:attr/textAppearanceLarge" which wasn't allowing for the layout to be inflated.

Don't know exactly why, (I'm still a bit new to Android - less than a year of experience), might have something to do with calling system attributes, idk, all I know is as soon as I used plain old @dimen/md_text_16sp (which is a custom of mine), problem solved :)

Hope this helps...

Democritus answered 19/1, 2016 at 17:48 Comment(1)
I had no fragments nor textSize android attribute. My error was related to a TextInputLayout with a custom style inheriting TextAppearance.AppCompat instead of Widget.Design.TextInputLayout: . #19875382Neo
W
1

I had this on a 4.4.2 device, but 5+ was fine. The cause: inside a custom view's initialisation, I was creating a TextView(Context context, AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes), which is API 21+.

Android Studio 2.1 doesn't complain about it even though it is annotated TargetApi(21). Apparently, Android Studio 2.2 will correct this and properly show it as an error.

Hope this helps someone.

Warily answered 7/6, 2016 at 2:23 Comment(0)
D
1

I am a bit late to the party but Non of these answer helped me in my case. I was using Google map as SupportMapFragment and PlaceAutocompleteFragment both in my fragment. As all the answers pointed to the fact that the problem is with SupportMapFragment being the map to be recreated and redrawn.

But I also had problem with PlaceAutocompleteFragment. So here is the working solution for those who are facing this problem because of SupportMapFragment and SupportMapFragment

 mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFragment);
    FragmentManager fm = getChildFragmentManager();

    if (mapFragment == null) {
        mapFragment = SupportMapFragment.newInstance();
        fm.beginTransaction().replace(R.id.mapFragment, mapFragment).commit();
        fm.executePendingTransactions();
    }

    mapFragment.getMapAsync(this);

    //Global PlaceAutocompleteFragment autocompleteFragment;


    if (autocompleteFragment == null) {
        autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autoCompleteFragment);

    }

And in onDestroyView clear the SupportMapFragment and SupportMapFragment

@Override
public void onDestroyView() {
    super.onDestroyView();


    if (getActivity() != null) {
        Log.e("res","place dlted");
        android.app.FragmentManager fragmentManager = getActivity().getFragmentManager();
        android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.remove(autocompleteFragment);
        fragmentTransaction.commit();

        autocompleteFragment = null;
    }


}
Downs answered 19/1, 2018 at 20:44 Comment(0)
A
1

In my particular case the problem was I added this line to a TextView :

android:background="?attr/selectableItemBackground"

After removing this, everything started to work fine.

Amadaamadas answered 3/6, 2020 at 19:7 Comment(0)
R
1

For me i copy paste an activity layout, and i didn't change the value in

<androidx.constraintlayout.widget.ConstraintLayout>
...
tools:context=""  <!-- Check this value -->
</androidx.constraintlayout.widget.ConstraintLayout>

after updating this with the new activity name, it worked for me.

Reube answered 3/4, 2021 at 16:29 Comment(0)
P
0

I think the basic problem is with "android:targetSdkVersion" which is defined in AndroidManifest.xml. In my case, the initial value which I have defined as:

android:targetSdkVersion=16

I changed it to:

android:targetSdkVersion=22

which resolved my all of the error. So, setting up the correct "targetSdkVersion" is also important before building an android app.

Protoplast answered 16/9, 2015 at 10:23 Comment(0)
M
0

In case someone else comes here and the answers do not help solve the problem, one more thing to try.

As others have mentioned, this usually is caused by an issue nested in the XML itself as opposed to something you did wrong in your Java. In my case, it was a super easy (and stupid) mistake to fix.

I had code like this:

<view
    android:layout_width="fill_parent"
    android:layout_height="1dip"
    android:id="@+id/view44"
    android:background="@color/gray"
    />

When all I had to do was capitalize the v in 'View' so that the system recogized it. Check that your custom views (Or Fragments, recyclerviews, etc) all have the proper capitalized declaration up front so that the XML auto-complete will match it to the appropriate view.

Monochromat answered 30/11, 2015 at 22:39 Comment(0)
B
0

I had this error too, and after very long debugging the problem seamed to be that my MainClass extended Activity instead of FrameActivity, in my case, the xml wasn't a problem. Hope to help you.

Benedikta answered 5/9, 2016 at 15:37 Comment(0)
O
0

In my case .

The layout i was trying to inflate had

<include 
 layout  = "...."
/>

tag, removing it fixed it.

I was trying to inflate a previous layout designed for a Actvity into the view-pager adapter.

Oldtime answered 30/6, 2017 at 9:58 Comment(0)
H
0

My error was caused by a different problem.

I was passing a bundle from an Activity to its fragment. When I commented the code receiving the bundle in the fragment the error was gone. As it turns out, my error was due to the below "getArguments();" part which was returning null.

Bundle args = getArguments();

Upon checking the Activity sending code, I realized I had a silly mistake in the below;

Bundle bundle =new Bundle();
 bundle.putInt("recipeID", recipe_position);
 Fragment mainFragment = new MainActivityFragment();
 mainFragment.setArguments(bundle);
 FragmentManager fragmentManager = getSupportFragmentManager();
 --> fragmentManager.beginTransaction()
                        .replace(R.id.container, new  MainActivityFragment(),
                                DetailRecipeActivityFragment.TAG)
                        .commit();

I was creating a NEW fragment in the line with the arrow. Whereas I should have used the pre-instantiated fragment that already had my bundle. So it should have been:

Bundle bundle =new Bundle();
 bundle.putInt("recipeID", recipe_position);
 Fragment mainFragment = new MainActivityFragment();
 mainFragment.setArguments(bundle);
 Fragment mainFragment = new MainActivityFragment();
 FragmentManager fragmentManager = getSupportFragmentManager();
 -->fragmentManager.beginTransaction()
                        .replace(R.id.container, mainFragment,
                                DetailRecipeActivityFragment.TAG)
                        .commit();

I don't know why exactly it throws this error instead of an NPE, but this solved my error in case someone is having the same scenario

Huffman answered 22/7, 2017 at 20:11 Comment(0)
A
0

I was having the same problem, in my case the package name was wrong, fixing it solved the problem.

Adopted answered 19/1, 2018 at 16:12 Comment(0)
C
0

Open the gradle.properties and add the following line:

android.enableAapt2=false

Reference: https://github.com/chrisjenx/Calligraphy/issues/417#issuecomment-365177808

Captive answered 12/3, 2018 at 2:51 Comment(1)
Android gives a warning that android.enableAapt2 is deprecated.Propaedeutic
O
0

I had this error when I had my RecyclerView at the root of my fragment.xml,

but when I wrapped it with a ViewGroup, the app worked fine.

Oncoming answered 21/10, 2018 at 20:38 Comment(0)
T
0

Are android:name and class: interchangeable?

Presumably, yes. I have only used class, and that seems to be what most of Google's examples use, but I do see where they use android:name in some samples. Unfortunately, there is no formal and complete documentation for fragment.

use

class = "com.fragment.NavigationDrawerFragment"

insted of

android:name="com.fragment.NavigationDrawerFragment"

That seemingly means that program looks "class" attribute first. And on fail looks "name" attribute. So as far as it's true using "class" if more efficient

Toshiatoshiko answered 15/1, 2020 at 5:14 Comment(0)
L
0

FWIW: I was getting "Android.Views.InflateException Message=Binary XML file line #1: Binary XML file line #1: Error inflating class android.view.TextureView"

I am new to android form design. In trying to put a border on some buttons I found an SO post that inspired me to create buttonborder.xml that looks like:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@android:color/transparent" />
<stroke android:width="1dp" android:color="@android:color/white"/>

Then for each button I added

android:background="@drawable/buttonborder"

However, in my enthusiasm I also added it to a TextureView - which was my problem. When I removed the line from the TextureView, things worked.

Lizzettelizzie answered 23/1, 2020 at 17:20 Comment(0)
S
0

Check Proguard

I had this error combined with a ClassNotFoundException for one of my classes, and ended up simply needing to check my proguard-rules.pro. That file is found under the app directory in your YourAppName directory. I needed to append the following two lines:

-keep class com.gbros.tabslite.data.** { *; }
-keepattributes Exceptions, Signature, InnerClasses 

Where tabslite is my app name, and the file I was getting a ClassNotFoundException was in the data folder.

Systematize answered 25/3, 2020 at 2:51 Comment(0)
D
0

This error is really confusing. In my case I was missing a default empty parameter less constructor for my fragment. After adding empty constructor in my fragment the problem resolved.

Doyon answered 17/4, 2020 at 13:52 Comment(0)
O
0

This exception may occurs when the activity which manages your fragments was stoped and you try to open it again, so in this case the NavHostFragment will be not reconized by activity which has losing the state. To fix it try to finish the cycle life of your activity in order to reload the NavHostFragment by the FrgamentManager again.

Inside your Activity where you manage your fragments put the below :

@Override
protected void onStop() {
    super.onStop();
    this.finishActivity(0);
}
Overword answered 20/5, 2020 at 0:2 Comment(0)
F
0

I also encountered this error.

Try-catching the method that threw the error, I found the solution to my specific problem.

In my case, I am using two standard themes: light & dark.

Because of this, I have had to (wherever necessary) apply color resource references to colors, drawables and views in this manner:

android:color="?accentColor"

so that the system will know which color to use depending on the current theme.

In my DrawerLayout, I have a custom selector for the ListView items (the menu):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="?colorAccent" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="?colorAccent" />
        </shape>
    </item>
</selector>

The lower APIs had thus far parsed these color references just fine. However, in this selector, it just didn't work.

Making one selector for each theme, changing any ?colorAccent to t1colorAccent and t2colorAccent respectively, solved my problem.

Foresight answered 11/3, 2021 at 14:13 Comment(0)
C
0

In my case I was using the Hilt Dagger Library and in my ViewModel class I did not mentioned @HiltViewModel annotation at the top of the class.

So just adding that annotation solved the issue. You can check if you have added annotations for all the activities and fragments too.

Caboose answered 27/9, 2021 at 1:57 Comment(0)
C
0

After 2 hours of struggle, I Found that my one drawable file was in v24 but I was testing app on Api 23 device. To Solve that crash Follow these steps:

  1. Make sure you have your files in res>drawable folder. instead of res>drawable-v24.
  2. Sometimes your android studio not showing drawable-24 folder and your file in res>drawable folder with v24 tag.
  3. Remove that file and re-add it.
Calycine answered 11/2, 2022 at 12:26 Comment(0)
D
0

My MainActivity was:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

And i placed AppCompatActivity instead of ComponentActivity:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

This solved my problem.

Dispersoid answered 14/8, 2023 at 16:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.