首页 > 解决方案 > 为什么当我想访问这个片段时,我的应用程序失败了?安卓工作室

问题描述

我正在开发一个应用程序,我想在 Firebase 中插入数据,但是当我想在应用程序中打开片段时出现错误。我正在使用 nav_graph 在屏幕之间导航,并且我也在使用movile_navigation。我不知道这是否是重要的信息。

这是java代码,我不知道是什么导致了错误:

```
    
        public class Pantalla1Fragment extends Fragment{
    TextView editTextName;
    TextView editTextEdad;
    TextView editTextApellidos;
    TextView editTextGenero;
    TextView editPadecimientos;
    TextView editTextObservaciones;
    TextView getEditTextTratamientos;
    Button btnRegistar;

    FirebaseAuth mAuth;
    DatabaseReference mDatabase;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public Pantalla1Fragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Pantalla1Fragment.
     */
    // TODO: Rename and change types and number of parameters
    public static Pantalla1Fragment newInstance(String param1, String param2) {
        Pantalla1Fragment fragment = new Pantalla1Fragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

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

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }*/

   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_pantalla1, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        editTextName = view.findViewById(R.id.editTextName);
        editTextEdad = view.findViewById(R.id.editTextEdad);
        editTextApellidos = view.findViewById(R.id.editTextApellidos);
        editTextGenero = view.findViewById(R.id.editTextGenero);
        editPadecimientos = view.findViewById(R.id.editTextPadesimientos);
        editTextObservaciones = view.findViewById(R.id.editTextObservaciones);
        getEditTextTratamientos = view.findViewById(R.id.editTextTratamientos);

        btnRegistar = view.findViewById(R.id.btnRegistar);



        btnRegistar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerPerfil();
            }
        });
    }

    public void registerPerfil() {
        String nombre=editTextName.getText().toString();
        String apellidos=editTextApellidos.getText().toString();
        String edad=editTextEdad.getText().toString();
        String genero=editTextGenero.getText().toString();
        String padecimientos=editPadecimientos.getText().toString();
        String tratamiento=getEditTextTratamientos.getText().toString();
        String observaciones=editTextObservaciones.getText().toString();

        if(!TextUtils.isEmpty(nombre)){
            String id=mDatabase.push().getKey();
            Registro_Perfiles perfil = new Registro_Perfiles(nombre, apellidos, edad, genero, padecimientos, tratamiento, observaciones);

            mDatabase.child("Users").child(id).setValue(perfil);
            //Toast.makeText(this, "Datos introducidos", Toast.LENGTH_LONG).show();
        }
    }
}
And this part is the fragment view:

   <?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=".Pantalla1Fragment">
   
   <ScrollView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent"
       android:padding="15dp"
       app:layout_constraintTop_toTopOf="parent">
   
       <LinearLayout
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:orientation="vertical">
   
           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:text="Nombre" />
   
           <EditText
               android:id="@+id/editTextName"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:hint="@string/editTextNombre" />
   
           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:text="Apellidos" />
   
           <EditText
               android:id="@+id/editTextApellidos"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:hint="Apellidos" />
   
           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:text="Edad" />
   
           <EditText
               android:id="@+id/editTextEdad"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:hint="Edad" />
   
           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:text="Genero" />
   
           <EditText
               android:id="@+id/editTextGenero"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:hint="Genero" />
   
           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:text="Padesimientos" />
   
           <EditText
               android:id="@+id/editTextPadesimientos"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:hint="Padesimientos" />
   
           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:text="Tratamientos" />
   
           <EditText
               android:id="@+id/editTextTratamientos"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:hint="Tratamientos" />
   
           <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:text="Observaciones" />
   
           <EditText
               android:id="@+id/editTextObservaciones"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:hint="Observaciones" />
   
           <Button
               android:id="@+id/btnRegistar"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginTop="10dp"
               android:text="REGISTRAR NUEVO PERFIL" />
   
       </LinearLayout>
   </ScrollView>
   
   </androidx.constraintlayout.widget.ConstraintLayout>

日志中的错误

    --------- beginning of crash
2020-08-26 12:13:05.893 17635-17635/com.example.thebestapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.thebestapp, PID: 17635
    java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.push()' on a null object reference
        at com.example.thebestapp.Pantalla1Fragment.registerPerfil(Pantalla1Fragment.java:126)
        at com.example.thebestapp.Pantalla1Fragment$1.onClick(Pantalla1Fragment.java:111)
        at android.view.View.performClick(View.java:6297)
        at android.view.View$PerformClick.run(View.java:24797)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6626)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)

标签: javaandroidandroid-studioandroid-fragments

解决方案


你永远不应该getActivity().findViewById在片段中使用。

相反,覆盖onViewCreated()并使用view.findViewById()-view传递给该方法的是您膨胀的视图onCreateView()

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        editTextName = view.findViewById(R.id.editTextName);
        editTextEdad = view.findViewById(R.id.editTextEdad);
        editTextApellidos = view.findViewById(R.id.editTextApellidos);
        editTextGenero = view.findViewById(R.id.editTextGenero);
        editPadecimientos = view.findViewById(R.id.editTextPadesimientos);
        editTextObservaciones = view.findViewById(R.id.editTextObservaciones);
        getEditTextTratamientos = view.findViewById(R.id.editTextTratamientos);

        btnRegistar = view.findViewById(R.id.btnRegistar);



        btnRegistar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                registerPerfil();
            }
        });
    }

推荐阅读