Adapter Problem

1

I have a problem in my RecyclerView.Adapter .

My mistake is as follows

  

java.lang.NullPointerException on: Attempt to invoke virtual method 'java.lang.String com.example.piipe.bienestapp.Modelos.usuario.getNombre ()' on a null object reference

I think that the problem is assigning the user model to the mSocial model when assigning it as null. Attached code in case you can help me. Thanks

Social.java

public class Social extends Fragment {

private List<mSocial> lSocial;
private RealmResults<mSocial> socialResult;

private RecyclerView socialRecyclerView;
private RecyclerView.Adapter socialAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private Realm mRealm;
private SwipeRefreshLayout swipeSocial;


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_social, container, false);

        mRealm = Realm.getDefaultInstance();

        socialResult = mRealm.where(mSocial.class).findAll();

        if (socialResult.size() == 0){
            if (MyUtilities.verificaConexion(getContext())){
                GetAlluser();
                GetAllPost();
            }
        }

        swipeSocial = v.findViewById(R.id.swipePost);
        lSocial = this.getAllPostFalso();

        socialRecyclerView = v.findViewById(R.id.listPost);
        mLayoutManager = new LinearLayoutManager(getActivity());

        socialAdapter = new socialAdapter(socialResult, R.layout.item_list_social, new socialAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(mSocial social, int position) {

            }
        });

        socialRecyclerView.setLayoutManager(mLayoutManager);
       socialRecyclerView.setAdapter(socialAdapter);

        swipeSocial.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (MyUtilities.verificaConexion(getActivity())){
                    GetAlluser();
                    GetAllPost();

                }else {
                    Toast.makeText(getActivity(), "Esta acción necesita conexión a internet, comprueba tu conexión", Toast.LENGTH_SHORT).show();
                    onItemsLoadComplete();
                }
            }
        });

    return v;
}

private RealmResults<usuario> listarUusuarios() {
    RealmResults<usuario> list = mRealm.where(usuario.class).findAll();
    return list;
}

private void GetAlluser() {
    if (MyUtilities.verificaConexion(getContext())) {
        RequestQueue queue = Volley.newRequestQueue(getContext());
        String URL = "http://www.nodclous.com/bienestapp/apiRcv/GetInfoAllUserBienestApp";

        JsonObjectRequest jsonReque = new JsonObjectRequest(Request.Method.GET, URL, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                                              try {
                            String status = response.getString("status");

                            JSONArray mensaje = response.getJSONArray("mensaje");

                            if (status.equals("success")) {
                                getAllNamesJson(mensaje);

                            } else {
                                Toast.makeText(getContext(), "Error no se puedo realizar la consulta", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // VolleyLog.d("JSONPost", "Error: " + error.getMessage());
                Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        queue.add(jsonReque);
    }
}

private ArrayList<usuario> getAllNames() {

    return new ArrayList<usuario>() {
        {
            add(new usuario(111111111, "nombre1","apellido1",0,"Masculino","Estudiante","1234","none"));
            add(new usuario(111111111, "nombre2","apellido2",0,"Masculino","Estudiante","1234","none"));
            add(new usuario(111111111, "nombre3","apellido3",0,"Masculino","Estudiante","1234","none"));
            add(new usuario(111111111, "nombre4","apellido4",0,"Masculino","Estudiante","1234","none"));
            add(new usuario(111111111, "nombre5","apellido5",0,"Masculino","Estudiante","1234","none"));
            add(new usuario(111111111, "nombre6","apellido6",0,"Masculino","Estudiante","1234","none"));
            add(new usuario(111111111, "nombre7","apellido7",0,"Masculino","Estudiante","1234","none"));
            add(new usuario(111111111, "nombre8","apellido8",0,"Masculino","Estudiante","1234","none"));
            add(new usuario(111111111, "nombre9","apellido9",0,"Masculino","Estudiante","1234","none"));
            add(new usuario(111111111, "nombre10","apellido10",0,"Masculino","Estudiante","1234","none"));


        }
    };
}

private ArrayList<mSocial> getAllPostFalso() {

    return new ArrayList<mSocial>() {
        {
            add(new mSocial(999999999, "titulo1","body1",null,0,0,0,null,"none"));
            add(new mSocial(999999999, "titulo2","body2",null,0,0,0,null,"none"));

        }
    };
}

private void getAllNamesJson(JSONArray mensaje) {

  /* mRealm.beginTransaction();
    mRealm.delete(usuario.class);
    mRealm.commitTransaction();*/

    try {

        if (mensaje.length() > 0) {

            for (int i = 0; i < mensaje.length(); i++) {
                JSONObject jsonObject = mensaje.getJSONObject(i);

                int rut = jsonObject.getInt("rutUsuario");
                String nombre = jsonObject.getString("nombreUsuario");
                String apellido = jsonObject.getString("apellidoUsuario");
                int edad = jsonObject.getInt("edadUsuario");
                String sexo = jsonObject.getString("sexoUsuario");
                String ocupacion = jsonObject.getString("ocupacionUsuario");
                String password = jsonObject.getString("passwordUsuario");
                String ruta = jsonObject.getString("rutaImagen");
                String img = jsonObject.getString("imgBase64");
                Log.d("Carga Usuario",nombre);
                usuario usuarioJson = new usuario(rut, nombre,apellido,edad,sexo,ocupacion,password,img);
                mRealm.beginTransaction();
                mRealm.copyToRealmOrUpdate(usuarioJson);
                mRealm.commitTransaction();
            }

        }

        mRealm.close();
       //onItemsLoadComplete();

    } catch (JSONException e) {
        e.printStackTrace();
    }

}

private void onItemsLoadComplete() {
    // Update the adapter and notify data set changed
    // ...

    // Stop refresh animation
    swipeSocial.setRefreshing(false);
}

private void imprimirUsuarios(){
    RealmResults<usuario> us= mRealm.where(usuario.class).findAll();

    for (int i = 0; i< us.size();i++){
        Log.d("Usuario",us.get(i).getNombre());
    }
}

private void imprimirSocial(){
    RealmResults<mSocial> us= mRealm.where(mSocial.class).findAll();

    for (int i = 0; i< us.size();i++){
        Log.d("TituloPost",us.get(i).getTituloPost());
    }
}

private void GetAllPost() {
    if (MyUtilities.verificaConexion(getContext())) {
        RequestQueue queue = Volley.newRequestQueue(getContext());
        String URL = "http://www.nodclous.com/bienestapp/apiRcv/GetSocial";

        JsonObjectRequest jsonReque = new JsonObjectRequest(Request.Method.GET, URL, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            String status = response.getString("status");

                            JSONArray mensaje = response.getJSONArray("mensaje");


                            if (status.equals("success")) {
                                getAllPostJson(mensaje);

                            } else {
                                Toast.makeText(getContext(), "Error no se puedo realizar la consulta", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // VolleyLog.d("JSONPost", "Error: " + error.getMessage());
                Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        queue.add(jsonReque);
    }
}

private void getAllPostJson(JSONArray mensaje) {
    //lSocial.clear();
   /* mRealm.beginTransaction();
    mRealm.delete(mSocial.class);
    mRealm.commitTransaction();*/

    try {

        if (mensaje.length() > 0) {

            for (int i = 0; i < mensaje.length(); i++) {
                JSONObject jsonObject = mensaje.getJSONObject(i);

                int rut = jsonObject.getInt("rutUsuario_fk");
                int idPost = jsonObject.getInt("idPublicacion");
                String titulo = jsonObject.getString("tituloPublicacion");
                String body = jsonObject.getString("bodyPublicacion");
                int reaccion1 = jsonObject.getInt("reaccion1");
                int reaccion2 = jsonObject.getInt("reaccion2");
                int reaccion3 = jsonObject.getInt("reaccion3");
                int idMeta_fk = jsonObject.getInt("idMeta_fk");
                String fechaPost = jsonObject.getString("fechaPost");
                Log.d("TituloPost","rutUsuario"+rut);
                mMeta metaPost = mRealm.where(mMeta.class).equalTo("idMeta",idMeta_fk).findFirst();
                usuario usuarioPost = mRealm.where(usuario.class).equalTo("rut",rut).findFirst();
           /*     Log.d("TituloPost","rutUsuario2 "+ usuarioPost.getNombre());
                Log.d("IMAGEN","IMAGEN "+ usuarioPost.getImagePerfil());*/

                lSocial.add(new mSocial(idPost, titulo,body,usuarioPost,reaccion1,reaccion2,reaccion3,metaPost,MyUtilities.CambiaFecha2(fechaPost)));

            }

        }
        mRealm.beginTransaction();
        mRealm.copyToRealmOrUpdate(lSocial);
        mRealm.commitTransaction();
        mRealm.close();
        socialRecyclerView.setAdapter(socialAdapter);
        socialAdapter.notifyDataSetChanged();
        onItemsLoadComplete();

    } catch (JSONException e) {
        e.printStackTrace();
    }
}}

socialAdapter.java

public class socialAdapter extends RecyclerView.Adapter<socialAdapter.ViewHolder>{


private List<mSocial> arrayList;
private int resource;

private OnItemClickListener itemClickListener;



public socialAdapter(List<mSocial> arrayList, int resource, OnItemClickListener listener) {
    this.arrayList = arrayList;
    this.resource = resource;
    this.itemClickListener = listener;
}

public void updateList(final ArrayList<mSocial> data) {
    arrayList = data;
    notifyDataSetChanged();
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(resource, parent, false);
    ViewHolder vh = new ViewHolder(v);
    return vh;

}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    holder.bind(arrayList.get(position),itemClickListener);
}

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

public static class ViewHolder extends RecyclerView.ViewHolder{


    TextView nombreSocial;
    TextView nameMetaSocial;
    TextView descriptionMetaSocial;
    TextView fechaSocial;
    CircleImageView imagenPerfil;
    TextView confiaText;
    IconButton confiaIcon;
    private Context context;

    public ViewHolder(View itemView) {
        super(itemView);
        this.nombreSocial = itemView.findViewById(R.id.nombreSocial);
        this.nameMetaSocial = itemView.findViewById(R.id.nombreMetaSocial);
        this.descriptionMetaSocial = itemView.findViewById(R.id.descripcionMetaSocial);
        this.imagenPerfil = itemView.findViewById(R.id.circleFotoSocial);
        this.confiaText = itemView.findViewById(R.id.badge_textView);
        this.confiaIcon = itemView.findViewById(R.id.badge_icon_button);
        this.context = itemView.getContext();
        this.fechaSocial = itemView.findViewById(R.id.fechaSocial);
    }

    public void bind(final mSocial social, final OnItemClickListener listener) {
        Log.d("DENTRO ADAPTER",social.getTituloPost());
        Log.d("DENTRO ADAPTER",social.getDatosUser().getNombre());

        if(!social.getDatosUser().getImagePerfil().equals("none")){
            String previouslyEncodedImage = social.getDatosUser().getImagePerfil();
            if (!previouslyEncodedImage.equalsIgnoreCase("")) {
                byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
                final Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
                imagenPerfil.setImageBitmap(bitmap);

            }
        }else {

            imagenPerfil.setImageResource(R.mipmap.ic_contacto_1);
        }


        nombreSocial.setText(social.getDatosUser().getNombre()+" "+social.getDatosUser().getApellido());
        nameMetaSocial.setText(social.getTituloPost());
        descriptionMetaSocial.setText(social.getBodyPost());
        fechaSocial.setText(social.getFechaPost());
        confiaIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int cont = Integer.parseInt(confiaText.getText().toString());
                cont = cont+1;
                confiaText.setText(String.valueOf(cont));
            }
        });
    }
}

public interface OnItemClickListener {
    void OnItemClick(mSocial social, int position);
}}

Complete exception

FATAL EXCEPTION: main
              Process: com.example.piipe.bienestapp, PID: 10724
              java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.piipe.bienestapp.Modelos.usuario.getNombre()' on a null object reference
                  at com.example.piipe.bienestapp.AdapterApp.socialAdapter$ViewHolder.bind(socialAdapter.java:96)
                  at com.example.piipe.bienestapp.AdapterApp.socialAdapter.onBindViewHolder(socialAdapter.java:62)
                  at com.example.piipe.bienestapp.AdapterApp.socialAdapter.onBindViewHolder(socialAdapter.java:28)
                  at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6673)
                  at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6714)
                  at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5647)
                  at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5913)
                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5752)
                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5748)
                  at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2232)
                  at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1559)
                  at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1519)
                  at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:614)
                  at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3812)
                  at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3225)
                  at android.view.View.measure(View.java:20236)
                  at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:2263)
                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                  at android.widget.ScrollView.onMeasure(ScrollView.java:547)
                  at android.view.View.measure(View.java:20236)
                  at android.support.v4.widget.SwipeRefreshLayout.onMeasure(SwipeRefreshLayout.java:622)
                  at android.view.View.measure(View.java:20236)
                  at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:716)
                  at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:462)
                  at android.view.View.measure(View.java:20236)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6427)
                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:747)
                  at android.widget.LinearLayout.onMeasure(LinearLayout.java:629)
                  at android.view.View.measure(View.java:20236)
                  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1632)
                  at android.view.View.measure(View.java:20236)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6427)
                  at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:739)
                  at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
                  at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
                  at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:809)
                  at android.view.View.measure(View.java:20236)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6427)
                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                  at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:141)
                  at android.view.View.measure(View.java:20236)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6427)
                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:747)
                  at android.widget.LinearLayout.onMeasure(LinearLayout.java:629)
                  at android.view.View.measure(View.java:20236)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6427)
                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
                  at android.view.View.measure(View.java:20236)
    
asked by Felipe J. Ramirez 08.05.2018 в 01:25
source

1 answer

0
  

I think that the problem is at the moment assign assign the   user model to the mSocial model assigns it as null.

Exactly that is the problem if mSocial has null value, when trying to obtain in your Adapter the value by means of getNombre() is done in an instance with null value.

In this case it strikes me that it does not make an error in:

social.getTituloPost()

but if in:

social.getDatosUser().getNombre()

in this part of the code:

 public void bind(final mSocial social, final OnItemClickListener listener) {
        Log.d("DENTRO ADAPTER",social.getTituloPost());
        Log.d("DENTRO ADAPTER",social.getDatosUser().getNombre());

        if(!social.getDatosUser().getImagePerfil().equals("none")){
            String previouslyEncodedImage = social.getDatosUser().getImagePerfil();
            if (!previouslyEncodedImage.equalsIgnoreCase("")) {
                byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
                final Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
                imagenPerfil.setImageBitmap(bitmap);

            }
        }else {

            imagenPerfil.setImageResource(R.mipmap.ic_contacto_1);
        }


        nombreSocial.setText(social.getDatosUser().getNombre()+" "+social.getDatosUser().getApellido());
 ...

You must make sure that the Post correctly obtains the data and in this case it seems to me that it is not necessary to call getDatosUser() , simply:

//social.getDatosUser().getNombre()
social.getNombre()

the same to obtain the other values.

    
answered by 08.05.2018 в 20:29