简体   繁体   中英

Error: Binary XML file line #9 in com.example.myfragment:layout/activity_main: Error inflating class fragment

I have been trying to put a recycler view inside a fragment and displaying the fragment in the main activity in Android Studio. It kept giving me and error inflating class fragment error. I don't know if it's the XML or the fragment code that contains the problems.

Error Code

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myfragment, PID: 11025
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfragment/com.example.myfragment.MainActivity}: android.view.InflateException: Binary XML file line #9 in com.example.myfragment:layout/activity_main: Binary XML file line #9 in com.example.myfragment:layout/activity_main: Error inflating class fragment
        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 #9 in com.example.myfragment:layout/activity_main: Binary XML file line #9 in com.example.myfragment:layout/activity_main: Error inflating class fragment
     Caused by: android.view.InflateException: Binary XML file line #9 in com.example.myfragment:layout/activity_main: Error inflating class fragment
     Caused by: java.lang.IllegalArgumentException: Binary XML file line #9: Must specify unique android:id, android:tag, or have a parent with an id for com.example.myfragment.AddExerciseFragment
        at androidx.fragment.app.FragmentManagerImpl.onCreateView(FragmentManagerImpl.java:3177)
        at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:134)
        at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
        at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:336)
        at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1069)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:997)
        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.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.example.myfragment.MainActivity.onCreate(MainActivity.java:18)
        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)
        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)

Here is my activity main

package com.example.myfragment;


import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import android.os.Bundle;
import android.view.View;

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }


}

activity_main

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<fragment
    android:name="com.example.myfragment.AddExerciseFragment"
    tools:layout="@layout/add_exercise_fragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:ignore="MissingConstraints"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Fragment Code

package com.example.myfragment;


import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;

public class AddExerciseFragment extends Fragment{
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    MainActivity activity;
    View view;

    public AddExerciseFragment(MainActivity activity) {
        this.activity = activity;
    }

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

        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new ExampleAdapter(activity);
        mRecyclerView.setAdapter(mAdapter);

        return view;
    }
}



Fragment XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/darker_gray"
        android:padding="4dp"
        android:scrollbars="vertical" />

</RelativeLayout>

Example Item

package com.example.myfragment;

import android.widget.Spinner;

public class ExampleItem {
    private String mWorkoutName;
    private String workoutNum;
    private String munit;
    private Spinner mUnitSpinner;
    public ExampleItem(String workoutName, String num, String unit) {
        mWorkoutName = workoutName;
        workoutNum = num;
        munit = unit;
    }

    public Spinner getmUnitSpinner() {
        return mUnitSpinner;
    }

    public void setSpinner (Spinner _mUnitSpinner) {
        mUnitSpinner = _mUnitSpinner;
    }


    public String getmWorkoutName() {
        return mWorkoutName;
    }

    public String getWorkoutNum() {
        return workoutNum;
    }

    public String getMunit() {
        return munit;
    }

    public void setmWorkoutName(String mWorkoutName) {
        this.mWorkoutName = mWorkoutName;
    }

    public void setWorkoutNum(String workoutNum) {
        this.workoutNum = workoutNum;
    }

    public void setMunit(String munit) {
        this.munit = munit;
    }


}


Example Item XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    android:id="@+id/addworkoutcardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/structurespinner"
    android:padding="5dp"
    app:cardCornerRadius="4dp"
    app:layout_constraintTop_toBottomOf="@+id/structurespinner"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

        <EditText
            android:id="@+id/number"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_toRightOf="@+id/workoutname"/>

        <EditText
            android:id="@+id/workoutname"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginEnd="19dp"
            android:ems="10"
            android:layout_marginRight="19dp" />

        <Spinner
            android:id="@+id/unitspinner"
            android:layout_width="120dp"
            android:layout_height="50dp"
            android:layout_marginStart="7dp"
            android:layout_toRightOf="@+id/number"
            android:entries="@array/workoutUnit"

            android:layout_toEndOf="@+id/number"
            android:layout_marginLeft="7dp" />

    </RelativeLayout>

</androidx.cardview.widget.CardView>

Recycler View Adapter

package com.example.myfragment;


import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import android.widget.ArrayAdapter;
import android.widget.EditText;

import android.widget.Spinner;


import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
    private Activity activity;
    private AddExerciseController controller;

    public ExampleAdapter(MainActivity activity) {
        this.activity = activity;
        this.controller = AddExerciseController.getController();
    }


    public static class ExampleViewHolder extends RecyclerView.ViewHolder {
        public EditText workoutName;
        public EditText workoutNum;
        public Spinner workoutUnit;

        public ExampleViewHolder(View itemView) {
            super(itemView);
            workoutName = itemView.findViewById(R.id.workoutname);
            workoutNum = itemView.findViewById(R.id.number);
            workoutUnit = itemView.findViewById(R.id.unitspinner);

            workoutUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> adapter, View v,
                                           int position, long id) {
                    // On selecting a spinner item
                    String sStep = adapter.getItemAtPosition(position).toString();

                    workoutUnit.setSelection(position);
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        }
    }



    @Override
    public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
        ExampleViewHolder evh = new ExampleViewHolder(v);
        return evh;
    }
    @Override
    public void onBindViewHolder(ExampleViewHolder holder, int position) {
        ExampleItem currentItem = controller.getListExercise().get(position);
        holder.workoutName.setText(currentItem.getmWorkoutName());
        holder.workoutNum.setText(currentItem.getWorkoutNum());

        currentItem.setSpinner(holder.workoutUnit);

        // store the spinner in the DetailItem object
        currentItem.setSpinner(holder.workoutUnit);

        // store DetailItem object in the array
        controller.getListExercise().set(position, currentItem);

    }

    @Override
    public int getItemCount() {
        return controller.getListExercise().size();
    }

Exercise Controller

package com.example.myfragment;

import java.util.ArrayList;
import java.util.List;

public class AddExerciseController {
    private List<ExampleItem> exampleList;
    private static AddExerciseController controller;

    public AddExerciseController(){
        initMovieList();
    }

    private List<ExampleItem> initMovieList(){

        if (this.exampleList == null) {

            this.exampleList = new ArrayList<ExampleItem>();
            exampleList.add(new ExampleItem("workout1","60", "seconds"));
            exampleList.add(new ExampleItem("workout2","50","seconds"));
            exampleList.add(new ExampleItem("workout3","5","seconds"));

             }
        return this.exampleList;
    }

    public List<ExampleItem> getListExercise() {
        return exampleList;
    }

    public static AddExerciseController getController(){
        if(controller == null){
            controller = new AddExerciseController();
        }
        return controller;
    }

}

The error message says:

Caused by: java.lang.IllegalArgumentException: Binary XML file line #9:
    Must specify unique android:id, android:tag, or have a parent with an id
    for com.example.myfragment.AddExerciseFragment

And if we look at your activity XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:name="com.example.myfragment.AddExerciseFragment"
        tools:layout="@layout/add_exercise_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:ignore="MissingConstraints"/>

</androidx.constraintlayout.widget.ConstraintLayout>

You'll note that your <fragment> tag does not have an android:id , android:tag , nor does your parent layout have an android:id . That's why you're getting the exception.

Therefore you can fix this by adding an android:id to your <fragment> tag (you also don't want to be using a ConstraintLayout with wrap_content sizes with a fragment - you want just a simple FrameLayout ):

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/add_exercise_fragment"
        android:name="com.example.myfragment.AddExerciseFragment"
        tools:layout="@layout/add_exercise_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>

It should be noted that Fragments must always have an empty constructor, so this code snippet is going to cause you to crash immediately afterwards:

public AddExerciseFragment(MainActivity activity) {
    this.activity = activity;
}

You should replace that constructor with a constructor with no parameters:

public AddExerciseFragment() {
}

You'll want to use getActivity() to retrieve the Activity, casting it to your MainActivity as needed.

I have got the same error but it was because of different issue.I would like to add this answer here. The same error is caused when you fail to mention a serializable data class in kotlin android room database. data class..(...):Serializable (check whether your data class is Serializaable)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM