The data is not shown in my table and the window is closed when trying to open it (it is a fragment)

1

This is my Logcat

  W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3f0c9795 time:379271637
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3f0c9795 time:379281329
W/IInputConnectionWrapper: endBatchEdit on inactive InputConnection
I/Timeline: Timeline: Activity_launch_request id:com.example.matias.taken time:379289386
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3f561be3 time:379290072
E/RecyclerView: No adapter attached; skipping layout
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.matias.taken, PID: 4507
                  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                      at co.quindio.sena.tutorialwebservice.adapter.UsuariosAdapter.onBindViewHolder(UsuariosAdapter.java:39)
                      at co.quindio.sena.tutorialwebservice.adapter.UsuariosAdapter.onBindViewHolder(UsuariosAdapter.java:16)
                      at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6482)
                      at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6515)
                      at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5458)
                      at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5724)
                      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5563)
                      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5559)
                      at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2229)
                      at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1556)
                      at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1516)
                      at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:608)
                      at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3693)
                      at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3109)
                      at android.view.View.measure(View.java:17438)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5470)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                      at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1083)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:615)
                      at android.view.View.measure(View.java:17438)
                      at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
                      at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
                      at android.view.View.measure(View.java:17438)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5470)
                      at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
                      at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
                      at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
Application terminated.

This is my Fragment where I request to show the data

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ConsultarListaUsuariosFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ConsultarListaUsuariosFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ConsultarListaUsuariosFragment extends Fragment implements Response.Listener<JSONObject>,Response.ErrorListener{
    // 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;

    private OnFragmentInteractionListener mListener;

    RecyclerView recyclerUsuarios;
    ArrayList<Usuario> listaUsuarios;

    ProgressDialog progress;

    RequestQueue request;
    JsonObjectRequest jsonObjectRequest;


    public ConsultarListaUsuariosFragment() {
        // 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 ConsultarListaUsuariosFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ConsultarListaUsuariosFragment newInstance(String param1, String param2) {
        ConsultarListaUsuariosFragment fragment = new ConsultarListaUsuariosFragment();
        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) {
        View vista=inflater.inflate(R.layout.fragment_consultar_lista_usuarios, container, false);

        listaUsuarios=new ArrayList<>();

        recyclerUsuarios= (RecyclerView) vista.findViewById(R.id.idRecycler);
        recyclerUsuarios.setLayoutManager(new LinearLayoutManager(this.getContext()));
        recyclerUsuarios.setHasFixedSize(true);

        request= Volley.newRequestQueue(getContext());

        cargarWebService();

        return vista;

    }

    private void cargarWebService() {

        progress=new ProgressDialog(getContext());
        progress.setMessage("Consultando...");
        progress.show();

        String ip="http://192.168.1.5";

        String url=ip+"/ejemploBDRemota/wsJSONConsultarLista.php";

        jsonObjectRequest=new JsonObjectRequest(Request.Method.GET,url,null,this,this);
        request.add(jsonObjectRequest);
        VolleySingleton.getIntanciaVolley(getContext()).addToRequestQueue(jsonObjectRequest);
    }

    @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.setRut(jsonObject.optInt("rut"));
                usuario.setNombre(jsonObject.optString("nombre"));
                usuario.setApellido(jsonObject.optString("apellido"));
                usuario.setCorreo(jsonObject.optString("correo"));
                usuario.setPas(jsonObject.optString("pas"));
                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();
        }

    }

    // TODO: Rename method, update argument and hook method into UI event
    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;
    }



    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

This is my Adapter Users, line 39 mark it with parentheses. This is: holder.txtPas.setText (listUsers.get (position) .getPas (). ToString ());

public class UsuariosAdapter extends RecyclerView.Adapter<UsuariosAdapter.UsuariosHolder>{

    List<Usuario> listaUsuarios;

    public UsuariosAdapter(List<Usuario> listaUsuarios) {
        this.listaUsuarios = listaUsuarios;
    }

    @Override
    public UsuariosHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View vista= LayoutInflater.from(parent.getContext()).inflate(R.layout.usuarios_list,parent,false);
        RecyclerView.LayoutParams layoutParams=new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        vista.setLayoutParams(layoutParams);
        return new UsuariosHolder(vista);
    }

    @Override
    public void onBindViewHolder(UsuariosHolder holder, int position) {
        holder.txtRut.setText(listaUsuarios.get(position).getRut().toString());
        holder.txtNombre.setText(listaUsuarios.get(position).getNombre().toString());
        holder.txtApellido.setText(listaUsuarios.get(position).getApellido().toString());
        holder.txtCorreo.setText(listaUsuarios.get(position).getCorreo().toString());
        (Esta es la linea 39) holder.txtPas.setText(listaUsuarios.get(position).getPas().toString());
    }

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

    public class UsuariosHolder extends RecyclerView.ViewHolder{

        TextView txtRut,txtNombre,txtApellido,txtCorreo,txtPas;

        public UsuariosHolder(View itemView) {
            super(itemView);
            txtRut= (TextView) itemView.findViewById(R.id.txtRut);
            txtNombre= (TextView) itemView.findViewById(R.id.txtNombre);
            txtApellido= (TextView) itemView.findViewById(R.id.txtApellido);
            txtCorreo= (TextView) itemView.findViewById(R.id.txtCorreo);
            txtPas= (TextView) itemView.findViewById(R.id.txtPas);

        }
    }
}
    
asked by Matías Nicolás Núñez Rivas 27.02.2018 в 14:04
source

1 answer

1

The reference you get from TextView has a null value:

  

java.lang.NullPointerException: Attempt to invoke virtual method   'void android.widget.TextView.setText (java.lang.CharSequence)' on a   null object reference

In this case the value of holder.txtPas is null because the reference in the .xml does not exist:

  @Override
    public void onBindViewHolder(UsuariosHolder holder, int position) {
     ...
     ...
     holder.txtPas.setText(listaUsuarios.get(position).getPas().toString());
     ...    
    }

You must ensure that TextView with id txtPas is in layout usuarios_list.xml .

    
answered by 27.02.2018 / 17:05
source