0

I am trying to get the email of the commenter in an app using Firebase database. I can get the comments from the same database/chiled, but the email is always null, without any crash from the app. The following are the codes used with a screenshot of the problem.

Comment.java:

package sa.edu.qu.coc.cocapps.blog;

public class Comment {

    private String comment, commentEmail;

    public Comment() {
    }

    public Comment(String comment, String commentEmail) {
        this.comment = comment;
        this.commentEmail = commentEmail;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public String getCommentEmail() {
        return commentEmail;
    }

    public void setCommentEmail(String commentEmail) {
        this.commentEmail = commentEmail;
    }
}

CommentsActivity.java: The problem actually is in this line: viewHolder.commentEmail.setText("Commented by: " + model.getCommentEmail());

package sa.edu.qu.coc.cocapps.blog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import sa.edu.qu.coc.cocapps.R;
import sa.edu.qu.coc.cocapps.login.MainActivity;
import sa.edu.qu.coc.cocapps.prefs.PreferencesActivity;

public class CommentsActivity extends AppCompatActivity implements View.OnClickListener {

    private Toolbar toolbar = null;
    private FloatingActionButton fab;
    private FirebaseAuth firebaseAuth;
    private FirebaseUser firebaseUser;
    private Comment comment;
    private RecyclerView commentsRecyclerView;
    private EditText postComment;
    private ProgressDialog progressDialog;
    private DatabaseReference commentsDatabaseReference;
    private String postKey = null;
    private SharedPreferences prefs;
    private Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;
        prefs = getSharedPreferences(PreferencesActivity.PREFS_KEY, Context.MODE_PRIVATE);
        switch (prefs.getInt("appColor", 0)) {
            case 0:
                activity.setTheme(R.style.AppTheme);
                break;

            case 1:
                activity.setTheme(R.style.GrayTheme);
                break;

            case 2:
                activity.setTheme(R.style.BlueTheme);
                break;

            case 3:
                activity.setTheme(R.style.MagentaTheme);
                break;
        }
        setContentView(R.layout.activity_comments);

        firebaseAuth = FirebaseAuth.getInstance();

        firebaseUser = firebaseAuth.getCurrentUser();

        if (firebaseUser == null) {
            // Not signed in, launch the MainActivity.
            Intent intent = new Intent(this, MainActivity.class);
            // To prevent the user from going back to the "CommentsActivity".
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
            return;
        }

        postKey = getIntent().getExtras().getString("post_id");

        commentsDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Comments");
        commentsDatabaseReference.keepSynced(true);

        initViews();
        initCommentsSection();

        setSupportActionBar(toolbar);

        switch (prefs.getInt("appColor", 0)) {
            case 0:
                activity.setTheme(R.style.AppTheme);
                break;

            case 1:
                toolbar.setBackgroundColor(Color.GRAY);
                break;

            case 2:
                toolbar.setBackgroundColor(Color.BLUE);
                break;

            case 3:
                toolbar.setBackgroundColor(Color.MAGENTA);
                break;
        }

        fab.setOnClickListener(this);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private void initViews() {

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        fab = (FloatingActionButton) findViewById(R.id.fab);
    }

    private void initCommentsSection() {

        commentsRecyclerView = (RecyclerView) findViewById(R.id.commentsRecyclerView);
        commentsRecyclerView.setHasFixedSize(true);
        commentsRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        FirebaseRecyclerAdapter<Comment, CommentHolder> commentAdapter = new
                FirebaseRecyclerAdapter<Comment, CommentHolder>(
                        Comment.class,
                        R.layout.row_comment,
                        CommentHolder.class,
                        commentsDatabaseReference.child(postKey)) {
                    @Override
                    protected void populateViewHolder(CommentHolder viewHolder,
                                                      Comment model, int position) {

                        viewHolder.comment.setText(model.getComment());
                        viewHolder.commentEmail.setText("Commented by: " + model.getCommentEmail());

                        switch (prefs.getInt("fontSize", 0)) {
                            case 0:
                                viewHolder.comment.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                                viewHolder.commentEmail.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                                return;

                            case 1:
                                viewHolder.comment.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                                viewHolder.commentEmail.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                                return;

                            case 2:
                                viewHolder.comment.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                                viewHolder.commentEmail.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                                return;

                            case 3:
                                viewHolder.comment.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
                                viewHolder.commentEmail.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
                                return;

                            case 4:
                                viewHolder.comment.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
                                viewHolder.commentEmail.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
                                return;
                        }
                    }
                };

        commentsRecyclerView.setAdapter(commentAdapter);

        postComment = new EditText(this);
        postComment.setHint(R.string.write_your_comment);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab:
                if (postComment.getParent() != null)
                    ((ViewGroup) postComment.getParent()).removeView(postComment);
                postComment.setText("");

                AlertDialog.Builder commentDialog = new AlertDialog.Builder(this)
                        .setTitle(R.string.what_are_you_thinking_about)
                        .setIcon(R.mipmap.write_comment)
                        .setView(postComment)
                        .setPositiveButton(R.string.send, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                if(postComment.getText() == null ||
                                        postComment.getText().toString().equals("") ||
                                        postComment.getText().toString().equals(" ") ||
                                        postComment.getText().toString().isEmpty())
                                    Snackbar.make(findViewById(R.id.root_activity_comments),
                                            R.string.the_comment_cannot_be_empty,
                                            Snackbar.LENGTH_LONG).show();
                                else
                                    sendComment();
                            }
                        })
                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                // Do not do anything.
                            }
                        });
                commentDialog.show();
                break;
        }
    }

    private void sendComment() {

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.commenting));
        progressDialog.show();

        comment = new Comment(postComment.getText().toString(), firebaseUser.getEmail());

        commentsDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                DatabaseReference newComment = commentsDatabaseReference.child(postKey).push();
                newComment.child("comment").setValue(comment.getComment());
                newComment.child("email").setValue(comment.getCommentEmail());
                newComment.child("postKey").setValue(postKey)
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful()) {
                                    progressDialog.dismiss();

                                    Toast.makeText(CommentsActivity.this, R.string.posted,
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                // TO DO: 1. Solve the problem of displaying email in comments.
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    protected static class CommentHolder extends RecyclerView.ViewHolder {
        private TextView comment, commentEmail;

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

            comment = (TextView) itemView.findViewById(R.id.commentTextView);
            commentEmail = (TextView) itemView.findViewById(R.id.commentEmail);
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}

the problem

And as you can see, the email is stored in the database without any problem.

Firebase database

I tried to use some solutions, like if(something != null) // Do following... but it still null, and some other Firebase related solutions, but also it still the same problem. So, I made this post looking for a solution.

KENdi
  • 7,576
  • 2
  • 16
  • 31
Androider
  • 159
  • 11

1 Answers1

2

Your POJO class Comment have a variable that is called "commentEmail", your database have an attribute that is called "email". Make the names match and it will work, don't forget getters and setters.

Firebase need the names in your class match with the names in the database to convert the node (dataSnapthot) in an instance of your class. If you want to keep the name as it is (can't see a reason why) there are annotations for it. Here is a question about Firebase and annotations:

Firebase @PropertyName doesn't work

That question explain variable must be public, but is set default, and I have read it can be private, the only condition is: getters and setter must be annotated as well. Maybe you can do some experiments and let us know.

cutiko
  • 9,887
  • 3
  • 45
  • 59