Tengo el siguiente codigo para cargar un recyclerview con cardview y en cada cardiew me muestra los empleados a los que se les presto equipo al iniciar el turno al igual que la fecha de el momento en que se carga el recyclerview y le agregue un boton para de esta manera almacenar la fecha en que el empleado devolvio el equipo prestado. Pero al momento de loguearme no me carga el fragment con mi recyclerview y me muestra el siguiente error
(android.view.View$OnClickListener)' on a null object reference
El codigo de mi fragment donde tengo el recycler es el siguiente
HomeFragment.java
package com.xcheko51x.buscadorrecyclerviewmysql.ui.home;
public class HomeFragment extends Fragment implements Response.Listener<JSONObject>,Response.ErrorListener{
private MenuItem menuItem;
private SearchView searchView;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
RecyclerView recyclerUsuarios;
ArrayList<Usuario> listaUsuarios;
Button btnActualizar;
ProgressDialog pDialog;
TextView txtentrega,txtid;
ProgressDialog progress;
// RequestQueue request;
JsonObjectRequest jsonObjectRequest;
StringRequest stringRequest;//SE MODIFICA
public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
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) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.navigation,menu);
super.onCreateOptionsMenu(menu, inflater);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View vista=inflater.inflate(R.layout.fragment_home, container, false);
txtentrega= (TextView) vista.findViewById(R.id.txtsalida);
txtid= (TextView) vista.findViewById(R.id.emid);
btnActualizar= (Button) vista.findViewById(R.id.btnexit);
listaUsuarios=new ArrayList<>();
recyclerUsuarios= (RecyclerView) vista.findViewById(R.id.idRecycler);
recyclerUsuarios.setLayoutManager(new LinearLayoutManager(this.getContext()));
recyclerUsuarios.setHasFixedSize(true);
// request= Volley.newRequestQueue(getContext());
cargarWebService();
//eventos botones
btnActualizar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
webServiceActualizar();
}
});
return vista;
}
private void cargarWebService() {
progress=new ProgressDialog(getContext());
progress.setMessage("Consultando...");
progress.show();
String ip=getString(R.string.ip);
String url=ip+"/ejemploBDRemota/wsJSONConsultarLista.php";
jsonObjectRequest=new JsonObjectRequest(Request.Method.GET,url,null,this,this);
// request.add(jsonObjectRequest);
VolleySingleton.getIntanciaVolley(getContext()).addToRequestQueue(jsonObjectRequest);
}
private void webServiceActualizar() {
pDialog=new ProgressDialog(getContext());
pDialog.setMessage("Cargando...");
pDialog.show();
String ip=getString(R.string.ip);
String url=ip+"/ejemploBDRemota/wsJSONUpdateMovil.php?";
stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pDialog.hide();
if (response.trim().equalsIgnoreCase("actualiza")){
// etiNombre.setText("");
// txtDocumento.setText("");
// etiProfesion.setText("");
Toast.makeText(getContext(),"Se ha Actualizado con exito",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(),"No se ha Actualizado ",Toast.LENGTH_SHORT).show();
Log.i("RESPUESTA: ",""+response);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),"No se ha podido conectar",Toast.LENGTH_SHORT).show();
pDialog.hide();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
String idem=txtid.getText().toString();
String salida=txtentrega.getText().toString();
Map<String,String> parametros=new HashMap<>();
parametros.put("fecha_sal",salida);
parametros.put("idem",idem);
return parametros;
}
};
//request.add(stringRequest);
VolleySingleton.getIntanciaVolley(getContext()).addToRequestQueue(stringRequest);
}
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "No se puede conectar "+error.toString(), Toast.LENGTH_LONG).show();
System.out.println();
Log.d("ERROR: ", error.toString());
progress.hide();
}
@Override
public void onResponse(JSONObject response) {
Usuario usuario=null;
JSONArray json=response.optJSONArray("usuario");
try {
for (int i=0;i<json.length();i++){
usuario=new Usuario();
JSONObject jsonObject=null;
jsonObject=json.getJSONObject(i);
usuario.setId(jsonObject.optString("Id"));
usuario.setReloj(jsonObject.optString("reloj"));
usuario.setNombre(jsonObject.optString("nombre"));
usuario.setArea(jsonObject.optString("area"));
usuario.setEquipo(jsonObject.optString("equipo"));
usuario.setFecha(jsonObject.optString("fecha_ent"));
listaUsuarios.add(usuario);
}
progress.hide();
UsuariosAdapter adapter=new UsuariosAdapter(listaUsuarios);
recyclerUsuarios.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(), "No se ha podido establecer conexión con el servidor" +
" "+response, Toast.LENGTH_LONG).show();
progress.hide();
}
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Este error me lo muestra en el siguiente metodo
//eventos botones
btnActualizar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
webServiceActualizar();
}
});
De igual manera hace referencia un error secundario hacia el Main
ActivityNavigationBinding.inflate(ActivityNavigationBinding.java:48)
NavigationActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityNavigationBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarNavigation.toolbar);
binding.appBarNavigation.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_list,R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
El error hace referencia a la siguiente seccion del metodo onCreate
binding = ActivityNavigationBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Anexo imagen del sistema cuando quito el codigo del boton actualizar
fragment_home.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=".ui.home.HomeFragment" >
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/idRecycler"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
usuarios_list.xml
?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
android:id="@+id/cvTarjeta"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="165dp"
card_view:cardElevation="4dp"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="177dp"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="149dp">
<TextView
android:id="@+id/txtArea"
android:layout_width="match_parent"
android:layout_height="24dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="54dp"
android:gravity="left"
android:hint="Area"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintHorizontal_bias="0.0"
card_view:layout_constraintStart_toStartOf="parent"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/txtEquipo"
android:layout_width="match_parent"
android:layout_height="24dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="30dp"
android:gravity="left"
android:hint="Equipo"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintHorizontal_bias="0.0"
card_view:layout_constraintStart_toStartOf="parent"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/txtFecha"
android:layout_width="match_parent"
android:layout_height="24dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="6dp"
android:gravity="left"
android:hint="Fecha"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintHorizontal_bias="0.0"
card_view:layout_constraintStart_toStartOf="parent"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/txtReloj"
android:layout_width="match_parent"
android:layout_height="24dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="112dp"
android:gravity="left"
android:hint="ID"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintHorizontal_bias="0.0"
card_view:layout_constraintStart_toStartOf="parent"
tools:ignore="RtlHardcoded" />
<TextView
android:id="@+id/txtNombre"
android:layout_width="match_parent"
android:layout_height="34dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="78dp"
android:gravity="left"
android:hint="Nombre"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintHorizontal_bias="0.0"
card_view:layout_constraintStart_toStartOf="parent"
tools:ignore="RtlHardcoded,SmallSp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="276dp"
tools:layout_editor_absoluteY="22dp">
<TextView
android:id="@+id/txtsalida"
android:layout_width="match_parent"
android:layout_height="24dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="48dp"
android:gravity="left"
android:hint="Salida"
android:textSize="12sp"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintHorizontal_bias="0.0"
card_view:layout_constraintStart_toStartOf="parent"
tools:ignore="RtlHardcoded" />
<TextView
android:id="@+id/txt1"
android:layout_width="match_parent"
android:layout_height="24dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="72dp"
android:gravity="left"
android:text="Hora de Retorno"
android:textSize="13dp"
android:textStyle="bold"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintHorizontal_bias="0.0"
card_view:layout_constraintStart_toStartOf="parent"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/emid"
android:layout_width="match_parent"
android:layout_height="24dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="112dp"
android:gravity="left"
android:hint="ID"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintHorizontal_bias="0.0"
card_view:layout_constraintStart_toStartOf="parent"
tools:ignore="RtlHardcoded" />
<Button
android:id="@+id/btnexit"
android:layout_width="70dp"
android:layout_height="34dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="4dp"
android:gravity="center"
android:text="Salida"
android:textSize="10sp"
card_view:layout_constraintBottom_toBottomOf="parent"
card_view:layout_constraintEnd_toEndOf="parent"
card_view:layout_constraintHorizontal_bias="1.0"
card_view:layout_constraintStart_toStartOf="parent"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
HomeFragment
, al parecer en ese layout no está el botón con idbtnexit
, por otra parte, si usas Data o View Binding, no deberías usarfindViewById
, sino referirte a los elementos directamente por medio debinding.elId