title: Android - how to display number of likes in a post using firebase
body: <p>i want to print the total no of likes for particular post.<strong>but it gives me an error in this code<code>long numOfLikes = dataSnapshot.child("likes").getValue(Long.class);</code> and the error is  Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference</strong>
  <a href="https://i.stack.imgur.com/xDQiU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xDQiU.jpg" alt="enter image description here"></a></p>
  
  <p>my code is</p>
  
  <pre><code> private void onLikeClicked(View v) {
      boolean isLiked = !btnLike.isSelected();
      final String currentUserKey = User.currentKey();
  
      DatabaseReference likes = FirebaseDatabase.getInstance().getReference().child(kDataLikeKey);
      DatabaseReference curLike = likes.child(mPostRef.getKey()).child(currentUserKey).child("likes");
      likes.addListenerForSingleValueEvent(new ValueEventListener() {
          @Override
          public void onDataChange(DataSnapshot dataSnapshot) {
              long numLikes = 0;
              if (dataSnapshot.exists()) {
                  boolean isLiked = !btnLike.isSelected();
                  if (isLiked) {
                      //If already liked then user wants to unlike the post
                      likes.setValue(numLikes - 1);
                  }
              } else {
  
                  //If not liked already then user wants to like the post
                  likes.setValue(numLikes + 1);
              }
  
          }
  
          @Override
          public void onCancelled(DatabaseError databaseError) {
  
          }
      });
  
      // update Model
      curLike.setValue(isLiked);
  
      // update UI
      btnLike.setSelected(isLiked);
      displayNumberOfLikes();
  
  }
  public void displayNumberOfLikes(){
      boolean isLiked = !btnLike.isSelected();
      final String currentUserKey = User.currentKey();
  
      DatabaseReference likes = FirebaseDatabase.getInstance().getReference().child(kDataLikeKey);
      DatabaseReference curLike = likes.child(mPostRef.getKey()).child(currentUserKey).child("likes");
      likes.addValueEventListener(new ValueEventListener(){
          @Override
          public void onDataChange(DataSnapshot dataSnapshot) {
              if(dataSnapshot.exists()){
                  long numOfLikes = dataSnapshot.child("likes").getValue(Long.class);
                  mlikecnt.setText(""+numOfLikes);
                  //Populate numOfLikes on post i.e. textView.setText(""+numOfLikes)
                  //This is to check if the user has liked the post or not
                  btnLike.setSelected(dataSnapshot.hasChild(currentUserKey));
              }
          }
  
          @Override
          public void onCancelled(DatabaseError databaseError) {
  
          }
      });
  }
  </code></pre>