bradworks
bradworks

Reputation: 89

Inflating a fragment in main activity brings an error

I want to be able to swap between two fragments in my main activity class. But when inflating the fragment my application crashes. Below is my code:

This is the XML code where my fragment will be placed

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:background="@drawable/rounded_dialog"
    android:orientation="vertical"
    app:behavior_hideable="false"
    app:behavior_peekHeight="56dp"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">


    <fragment
        android:id="@+id/fragment_place"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"/>


</LinearLayout>

This is the code for my Fragment

 import android.os.Bundle;
    import androidx.fragment.app.Fragment;
    import androidx.recyclerview.widget.LinearLayoutManager;
    import androidx.recyclerview.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    import com.example.user.swim.AsyncTasks.GeoCodingTask;


    public class SearchLocation extends Fragment {
    private EditText destination;
    private Button search;
    private RecyclerView recyclerView;

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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.fragment_search_locatiom,  null);

        search = view.findViewById(R.id.search_destination);
        destination = view.findViewById(R.id.destination);
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        searchLocation(view);


        return view;
    }

Below is the code in my main activity to inflate the layout

    protected void onCreate(Bundle savedInstanceState) {


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

        if(findViewById(R.id.fragment_place)!=null){


            if (savedInstanceState != null) {
                return;
            }

            SearchLocation fragment = new SearchLocation();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_place, fragment).commit();

        }

I get the following errors in my logcat:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.swim, PID: 20462
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.swim/com.example.user.swim.MainActivity}: android.view.InflateException: Binary XML file line #29: Binary XML file line #14: Error inflating class fragment
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6540)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 Caused by: android.view.InflateException: Binary XML file line #29: Binary XML file line #14: Error inflating class fragment
 Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class fragment
 Caused by: java.lang.NullPointerException
    at java.lang.VMClassLoader.findLoadedClass(Native Method)
    at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at android.app.Fragment.instantiate(Fragment.java:617)
    at android.app.FragmentContainer.instantiate(FragmentContainer.java:49)
    at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3598)
    at android.app.FragmentController.onCreateView(FragmentController.java:98)
    at android.app.Activity.onCreateView(Activity.java:6182)
    at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:338)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:783)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:866)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:827)
    at android.view.LayoutInflater.parseInclude(LayoutInflater.java:995)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:862)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:827)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
    at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
    at com.example.user.swim.MainActivity.onCreate(MainActivity.java:87)
    at android.app.Activity.performCreate(Activity.java:6980)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at 
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6540)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

This is the XML for fragment_search_locatiom

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">


    <TextView
        android:layout_width="match_parent"

        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_margin="10dp"
        android:text="@string/where_would_you_like_to_go"
        android:textAlignment="center" />



    <EditText
        android:id="@+id/destination"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="10dp"
        android:drawablePadding="5dp"
        android:drawableStart="@drawable/ic_search_black_24dp"
        android:drawableLeft="@drawable/ic_search_black_24dp"
        android:textSize="18sp"
        android:inputType="text"
        android:background="@drawable/rectangle"
        android:hint="Search for destination"
        android:maxLines="1"
        android:imeOptions="actionDone"

        android:textAlignment="textStart" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/search_destination"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/search_destination" />



</LinearLayout>

I don't want to add the name/class attribute in the XML for the fragment because when you look at the official documentation adding those attributes won't make it possible to change fragments at runtime.

Also i've tried changing the MainActivity class to extend ActivityFragment but after more research i've discovered that ActivityFragment is a subclass of AppCompatActivity.

Upvotes: 1

Views: 50

Answers (2)

Jakir Hossain
Jakir Hossain

Reputation: 3930

You can try with Framelayout instead of fragment like the following

<!-- Framelayout to display Fragments -->
<FrameLayout
    android:id="@+id/fragment_place"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF" />

Upvotes: 0

Mekontso Sa&#39;a
Mekontso Sa&#39;a

Reputation: 61

i have copied your code and try to use it,when i use fragment in the SearchLocation it makes error so i changed it to Framlayout. Can't realy tell what is wrong in your code but this worked after i made changes MainActivity

public class MainActivity extends AppCompatActivity {

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

        if (findViewById(R.id.fragment_place) != null) {


            if (savedInstanceState != null) {
                return;
            }
            SearchLocation fragment = new SearchLocation();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_place, fragment).commit();
        }
    }

SearchLocation java


import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;



public class SearchLocation extends Fragment {

    private EditText mSearch;
    private Button mDestination;
    private RecyclerView mRecyclerView;

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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

         View view = inflater.inflate(R.layout.fragment_search_location, null);

        mSearch = view.findViewById(R.id.search_destination);
        mDestination = view.findViewById(R.id.destination);
        mSearch.setText("Hello world");
        RecyclerView mRecyclerView = view.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        /*searchLocation(view);*/

        return view;

    }

search_location 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=".SearchLocation">

    <EditText
        android:id="@+id/search_destination"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/destination"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/search_destination" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="32dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/destination" />
</androidx.constraintlayout.widget.ConstraintLayout>

Upvotes: 2

Related Questions