0

In my blog App in post detail Activity i added comments list with simple RecyclerView Adapter that was working fine but i am not able to add delete button for comment so moved to FireBase RecyclerView now i have lots of problems

  1. it not updating in real time
  2. when i comment that not pop out above the edit text layout when i close edit text box then it show my comments
  3. when i write a comment and hit comment button it not show comment but when i writing the second comment on same time after writing three or four line the previous comment pop out and the edit text bot hide under the keyboard why this happening

Activity Code:

mCommentsRecycler.setLayoutManager(mlinearLayoutManager);


}
@Override
public void onStart() {
 super.onStart();

 // Add value event listener to the post
 // [START post_value_event_listener]
 ValueEventListener postListener = new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
   // Get Post object and use the values to update the UI
   Post post = dataSnapshot.getValue(Post.class);
   // [START_EXCLUDE]
   // mAuthorView.setText(post.author);
   mTitleView.setText(post.title);
   mBodyView.setText(post.body);
   final String formImage = String.valueOf(post.postDetailPic);
   // [END_EXCLUDE]
   if (formImage.length() > 0) {
    Picasso.with(getApplicationContext()).load(formImage)
     .networkPolicy(NetworkPolicy.OFFLINE)
     .into(postPic, new Callback() {
      @Override
      public void onSuccess() {

      }

      @Override
      public void onError() {
       //Try again online if cache failed
       Picasso.with(getApplicationContext())
        .load(formImage)
        //.error(R.drawable.ic_warning_black_24dp)
        .into(postPic, new Callback() {
         @Override
         public void onSuccess() {

         }

         @Override
         public void onError() {
          Log.v("Picasso", "Could not fetch image");
         }
        });
      }
     });

   }

  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
   // Getting Post failed, log a message
   Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
   // [START_EXCLUDE]
   Toast.makeText(PostDetailActivity.this, "Failed to load post.",
    Toast.LENGTH_SHORT).show();
   // [END_EXCLUDE]
  }
 };
 mPostReference.addValueEventListener(postListener);
 // [END post_value_event_listener]

 // Keep copy of post listener so we can remove it when app stops
 mPostListener = postListener;


 // Listen for comments
 mAdapter = new CommentAdepter(Comment.class, CommentViewHolder.class, R.layout.item_comment, mCommentsReference, this);
 mCommentsRecycler.setAdapter(mAdapter);


}


@Override
public void onStop() {
 super.onStop();

 // Remove post value event listener
 if (mPostListener != null) {
  mPostReference.removeEventListener(mPostListener);
 }

 // Clean up comments listener
 mAdapter.cleanup();
}

@Override
public void onClick(View v) {
 int i = v.getId();
 if (i == R.id.button_post_comment) {
  postComment();
 }
}


private void postComment() {
 FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
 assert mUser != null;
 final String uid = mUser.getUid();
 final DatabaseReference commentDb = FirebaseDatabase.getInstance().getReference().child("Users").child(uid);
 commentDb.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
   // Get user information
   User user = dataSnapshot.getValue(User.class);
   String authorName = user.name;
   String commentUserPic = user.ProfilePic;


   // Create new comment object
   String commentText = mCommentField.getText().toString();

   HashMap < String, Object > dateCreated; {

    //Otherwise make a new object set to ServerValue.TIMESTAMP
    dateCreated = new HashMap < String, Object > ();
    dateCreated.put("timeStamp", ServerValue.TIMESTAMP);

   }
   HashMap < String, Boolean > commenter_id; {
    commenter_id = new HashMap < String, Boolean > ();
    commenter_id.put(getUid(), true);
   }
   Comment comment = new Comment(uid, authorName, commentText, commentUserPic, dateCreated, commenter_id);

   // Push the comment, it will appear in the list
   mCommentsReference.push().setValue(comment);


   // Clear the field
   mCommentField.setText(null);

  }

  @Override
  public void onCancelled(DatabaseError databaseError) {

  }

 });

}

private String getUid() {
 return FirebaseAuth.getInstance().getCurrentUser().getUid();
}


private static class CommentViewHolder extends RecyclerView.ViewHolder {

 public CommentViewHolder(View itemView) {
  super(itemView);

  authorView = (TextView) itemView.findViewById(R.id.comment_author);
  bodyView = (TextView) itemView.findViewById(R.id.comment_body);
  postingTime = (TextView) itemView.findViewById(R.id.comment_post_time);
  rm_comment = (Button) itemView.findViewById(R.id.remove_comment);


 }

 public void setImage(String images) {
  this.imageDp = images;
  userPic = (ImageView) itemView.findViewById(R.id.comment_photo);
  Picasso.with(context).load(imageDp).into(userPic);
 }


 void bindToPost(Comment comment, View.OnClickListener starClickListener) {
  authorView.setText(comment.author);
  bodyView.setText(comment.text);
  setImage(comment.commentPic);
  setViewValue(comment.getTimestampCreatedLong());

  rm_comment.setOnClickListener(starClickListener);
 }

}




private class CommentAdepter extends FirebaseRecyclerAdapter < Comment, CommentViewHolder > {
 private Context mContext;
 private List < String > mCommentIds = new ArrayList < > ();
 private List < Comment > mComments = new ArrayList < > ();
 private String mkey;

 CommentAdepter(Class < Comment > CommentClass, Class < CommentViewHolder > viewHolderClass, int modelLayout, DatabaseReference ref, final Context context) {
  super(CommentClass, modelLayout, viewHolderClass, mCommentsReference);


  mContext = context;

  // Create child event listener
  // [START child_event_listener_recycler]
  ChildEventListener childEventListener = new ChildEventListener() {
   @Override
   public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
    Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
    // A new comment has been added, add it to the displayed list
    Comment comment = dataSnapshot.getValue(Comment.class);
    // mkey = dataSnapshot.getKey();


    // [START_EXCLUDE]
    // Update RecyclerView
    mCommentIds.add(dataSnapshot.getKey());
    mComments.add(comment);
    notifyItemInserted(mComments.size() - 1);
    // [END_EXCLUDE]
   }

   @Override
   public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
    Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());

    // A comment has changed, use the key to determine if we are displaying this
    // comment and if so displayed the changed comment.
    Comment newComment = dataSnapshot.getValue(Comment.class);
    String commentKey = dataSnapshot.getKey();

    // [START_EXCLUDE]
    int commentIndex = mCommentIds.indexOf(commentKey);
    if (commentIndex > -1) {
     // Replace with the new data
     mComments.set(commentIndex, newComment);

     // Update the RecyclerView
     notifyItemChanged(commentIndex);
    } else {
     Log.w(TAG, "onChildChanged:unknown_child:" + commentKey);
    }
    // [END_EXCLUDE]
   }

   @Override
   public void onChildRemoved(DataSnapshot dataSnapshot) {
    Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());

    // A comment has changed, use the key to determine if we are displaying this
    // comment and if so remove it.
    String commentKey = dataSnapshot.getKey();


    // [START_EXCLUDE]
    int commentIndex = mCommentIds.indexOf(commentKey);
    if (commentIndex > -1) {
     // Remove data from the list
     mCommentIds.remove(commentIndex);
     mComments.remove(commentIndex);

     // Update the RecyclerView
     notifyItemRemoved(commentIndex);
    } else {
     Log.w(TAG, "onChildRemoved:unknown_child:" + commentKey);
    }
    // [END_EXCLUDE]
   }

   @Override
   public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
    Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());

    // A comment has changed position, use the key to determine if we are
    // displaying this comment and if so move it.
    Comment movedComment = dataSnapshot.getValue(Comment.class);
    String commentKey = dataSnapshot.getKey();

    // ...

   }

   @Override
   public void onCancelled(DatabaseError databaseError) {
    Log.w("PostDetailActivity", "postComments:onCancelled", databaseError.toException());
    Toast.makeText(mContext, "Failed to load comments.",
     Toast.LENGTH_SHORT).show();
   }


  };

  ref.addChildEventListener(childEventListener);
  // [END child_event_listener_recycler]

  // Store reference to listener so it can be removed on app stop
 }


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

 @Override
 protected void populateViewHolder(final CommentViewHolder viewHolder, final Comment model, final int position) {
  final DatabaseReference commentRef = getRef(position);
  final String commentKey = commentRef.getKey();

  if (model.commenter_id.containsKey(gUid())) {
   viewHolder.rm_comment.setVisibility(View.VISIBLE);
  }
  viewHolder.bindToPost(model, new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    Toast.makeText(mContext, "clicked  " + commentKey, Toast.LENGTH_SHORT).show();
    mCommentsReference.child(commentKey).removeValue();

   }
  });
 }

}

private String gUid() {
 return FirebaseAuth.getInstance().getCurrentUser().getUid();
}

}

if u need layout file please comment....

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
Yash Pal
  • 51
  • 6
  • There is a lot of code here. While maybe somebody will take the time to go through it, you'll find that you get a lot more answers if you limit the code to the minimum that is needed to reproduce the problem. To learn why that is and how to create such an MCVE, see http://stackoverflow.com/help/mcve – Frank van Puffelen Nov 03 '16 at 18:37

1 Answers1

0

I added ability to delete an item in a FirebaseRecyclerAdapter and generally followed the advice in this post:

how to implement a SetOnItemClickListener FirebaseRecyclerViewAdapter

I used the first solution, adding an ImageView.setOnClickListener() call within populateViewHolder(). Its working fine for me.

I'm not quite sure what the #3 problem is above but I was having a problem whereby the data didn't get populated the first time it was called. I found my solution in this post, namely ensuring that the RecyclerView height was set to match_parent:

FirebaseRecyclerAdapter - populateViewHolder is not populating the data for first time it runs?

Community
  • 1
  • 1
Lucy
  • 436
  • 5
  • 8
  • did u check the delete button work properly i having a problem when i delete any comment it not remove that comment but it remove the newly added comment in list.... – Yash Pal Nov 08 '16 at 04:04
  • Yes, my delete is working OK. Try debugging your scenario starting with 0 posts and then adding a new one and then with 1 post and adding a new one. Compare the key values to what is in Firebase via your browser. It may reveal news about where the problem lies. – Lucy Nov 10 '16 at 01:48