0

This is my class

public static class FeedItem {
    public int likesCount;
    public boolean isLiked;

    public FeedItem(int likesCount, boolean isLiked) {
        this.likesCount = likesCount;
        this.isLiked = isLiked;
    }
}

This is the other class where i utilised the FeedItem Class

class PostViewHolder extends RecyclerView.ViewHolder {
    FeedItem feedItem;
    FeedItem getFeedItem() {
        return feedItem;
    }
}

Then i use it in an animation file

FeedItemHolderInfo feedItemHolderInfo = (FeedItemHolderInfo) preInfo;
FeedAdapter.PostViewHolder holder = (FeedAdapter.PostViewHolder) newHolder;

animateHeartButton(holder);
updateLikesCounter(holder, holder.getFeedItem().likesCount);

Now in the MainActivity has a method where i update the arraylist

public void updateItems(boolean animated) {
    feedItems.clear();
    feedItems.addAll(Arrays.asList(
            new FeedItem(33, false),
            new FeedItem(1, false),
            new FeedItem(223, false),
            new FeedItem(2, false),
            new FeedItem(6, false),
            new FeedItem(8, false),
            new FeedItem(99, false)
    ));
    if (animated) {
        notifyItemRangeInserted(0, feedItems.size());
    } else {
        notifyDataSetChanged();
    }
}

But the app crashes at point

updateLikesCounter(holder, holder.getFeedItem().likesCount);

With the error being shown as

java.lang.NullPointerException: Attempt to read from field 'int com.example.alsongdunstan.thefaithapp.ui.adapter.FeedAdapter$FeedItem.likesCount' on a null object reference

Here i have even tried initialising the object from MainActivity before i call the updateItems Method

itemList.add(new FeedAdapter.FeedItem(124,false));

Though another error arises which i dont want. Some here Thanks

ColdFire
  • 6,764
  • 6
  • 35
  • 51

1 Answers1

0

The thing is, when you call holder.getFeedItem() it returns null pointer. The reason of this:

class PostViewHolder extends RecyclerView.ViewHolder {
  FeedItem feedItem;
  FeedItem getFeedItem() {
        return feedItem;
    },

as u can see there is no constructor where this field is set or even simple setter.

To fix it you can create a simple costructor which will set that field or get feed item in different way.

Maksym V.
  • 2,877
  • 17
  • 27