I'm having trouble passing the data to my recycler view

2685 views java
-3

I am having trouble passing the data to my recycle view. The data is taken in the firebase, but when I try to pass through (post= d.getValue(Post.class)) the null value is passed, but the variable d holds the data from the firebase. I always get a NullPointerException.

My FRAGMENT

    public class HomeFragment extends Fragment {
    // Components
    RecyclerView rv_posts;
    private FancyButton mBtAnunciar;
    // Vars
    List<Post> postsList;
    // Utils
    PostAdapter postAdapter;
    SharedPreferences sharedPreferences;
    // Firebase Utils
    private DatabaseReference mdataRef;
    private SearchView searchView;

    public HomeFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Init Main
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        // Setup Utils
        sharedPreferences = getActivity().getSharedPreferences("maisVidaSP", Context.MODE_PRIVATE);
        rv_posts = view.findViewById(R.id.rv_posts);
        rv_posts.setHasFixedSize(true);
        // Init Components
        searchView  = view.findViewById(R.id.pesquisar);
        mBtAnunciar = view.findViewById(R.id.btn_anunciar);
        postsList = new ArrayList<Post>();
        // Setup Components
        mBtAnunciar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                AnuncioFragment anuncioFragment = new AnuncioFragment();
                fragmentManager.beginTransaction().replace(R.id.fl_framelayout, anuncioFragment).commit();
            }
        });
        // Setup RecyclerView
        if (getActivity() != null){
            rv_posts.setLayoutManager(new CustomLinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL,false)); // set the list layout style to vertical.
            postAdapter = new PostAdapter(getActivity(), postsList);
            rv_posts.setAdapter(postAdapter);
        }
        // get the user's UID
        FirebaseAuth firebaseAuth = ConfiguracaoFirebase.getFirebaseAuth();
        String uid = firebaseAuth.getUid();
        mdataRef = ConfiguracaoFirebase.getFirebase();
        mdataRef.child("Usuario").orderByChild("disponibilidade").equalTo("Sim").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Post post = new Post();
               for (DataSnapshot d: dataSnapshot.getChildren()){
                   post= d.getValue(Post.class);
                    Log.i("MV","AQUI"+post);
                }
                postsList.add(post);
                postAdapter.notifyDataSetChanged();
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // todo: remove on production...
                Toast.makeText(getContext(), "Bugged", Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }
    public class CustomLinearLayoutManager extends LinearLayoutManager {
        public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }
    }

}

My class adapter

    public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {

    private List<Post> mPostsList;
    public Context mContext;
    private AdapterView.OnItemClickListener onItemClickListener;

    public PostAdapter(Context context, List<Post> postsList) {
        mContext = context;
        mPostsList = postsList;
    }
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(R.layout.posts_list, viewGroup, false);
        return new PostViewHolder(view, mContext);
    }
    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, final int position) {
        if ((mPostsList != null) && (mPostsList.size() >0)) {
            Post post = mPostsList.get(position);
            holder.tv_nome.setText(post.nome);
            holder.tv_provincia.setText(post.provincia);
            setChipTextAndBackground(holder.tv_estado, post.getEstado());
             holder.mli_tipoSangue.setLetter(post.getTipoSanguineo());
        }
    }
    @Override
    public int getItemCount() {
        return mPostsList.size();
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void onIt

answered question

1 Answer

6

In your example you add to the local copy of the list and not the one stored in your PostAdapter.

Post post = new Post();
for (DataSnapshot d: dataSnapshot.getChildren()){
    post= d.getValue(Post.class);
    Log.i("MV","AQUI"+post);
}
postsList.add(post);// <----------
postAdapter.notifyDataSetChanged();

Notice on that line that the postsList isn't stored in the PostAdapter, but in your HomeFragment.

In order to fix this, either make postAdapter.mPostsList not private and edit the field directly instead of the copy in the HomeFragment, or add the value via a method, e.g. postAdapter.addPost(post)

posted this

Have an answer?

JD

Please login first before posting an answer.