Description of the problem:
I have an activity with a button. This button opens another activity which contains a fragment. For some strange reason when touching the button, the app. it crashes
JAVA code of the activity that contains the fragment:
public class categorias extends AppCompatActivity {
private Fragment fragment_categorias;
private FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorias);
fragment_categorias = new fragment_musica();
ft.replace(R.id.fragment_categorias,fragment_categorias).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
}
}
XML code of the activity that contains the fragment:
<?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="com.example.ui.INICIO.RESULTADOS.CATEGORIAS.categorias"
android:contentDescription="@string/ayuda">
<fragment
android:id="@+id/fragment_categorias"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/et_buscar"
android:contentDescription="@string/ayuda"/>
</androidx.constraintlayout.widget.ConstraintLayout>
I attach the error that Android Studio throws me:
Caused by: android.view.InflateException: Binary XML file line #71: Binary XML file line #71: Error inflating class fragment Caused by: android.view.InflateException: Binary XML file line #71: Error inflating class fragment Caused by: java.lang.NullPointerException
Regarding the error, in your Fragment you are referring to an element with id
et_buscar
which does not exist in the layout:You must consider something important:
If you want to "replace" a Fragment, you can only replace a dynamically added Fragment". Fragments defined in a layout cannot be replaced.
Therefore instead of a Fragment:
use one
FrameLayout
in which you don't define a Fragment, but you can perform Fragment replacements inside this element: