用户登录后,来自Firebase数据库的评论的电子邮件为空

时间:2017-08-29 11:07:25

标签: java android firebase firebase-realtime-database

我正在尝试使用Firebase数据库在应用中收到评论者的电子邮件。我可以从同一个数据库/ chiled获得评论,但电子邮件总是null,没有任何应用程序崩溃。以下是与问题屏幕截图一起使用的代码。

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: 问题实际上在这一行: 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

正如您所看到的,电子邮件存储在数据库中没有任何问题。

Firebase database

我尝试使用某些解决方案,例如if(something != null) // Do following...但它仍然是null,以及其他一些与Firebase相关的解决方案,但它仍然存在同样的问题。所以,我在这篇文章中寻找解决方案。

1 个答案:

答案 0 :(得分:2)

您的POJO类Comment有一个名为&#34; commentEmail&#34;的变量,您的数据库有一个名为&#34; email&#34;的属性。使名称匹配,它将起作用,不要忘记吸气剂和制定者。

Firebase需要您的类中的名称与数据库中的名称匹配,以转换您的类实例中的节点(dataSnapthot)。如果你想保持名称不变(看不出原因),就会有注释。以下是有关Firebase和注释的问题:

Firebase @PropertyName doesn't work

那个问题解释变量必须是公共的,但是设置为默认值,我读过它可以是私有的,唯一的条件是:getters和setter也必须注释。也许你可以做一些实验并让我们知道。