2017-08-29 55 views
0

我正在嘗試使用Firebase數據庫在應用中獲取評論者的電子郵件。我可以從同一個數據庫/ chiled獲得評論,但電子郵件始終是null,沒有任何應用程序崩潰。以下是與問題的屏幕截圖一起使用的代碼。用戶登錄後,Firebase數據庫中的評論電子郵件爲空

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,以及其他一些相關的火力地堡的解決方案,而且它仍然同樣的問題。所以,我讓這個帖子尋找一個解決方案。

+0

我們預計手動計數到150嗎?你可以發佈[mcve]嗎? –

+0

@ M.Prokhorov對不起,我認爲行號出現在這裏,帖子更新。 – Androider

回答

2

您的POJO類Comment有一個名爲「commentEmail」的變量,您的數據庫有一個名爲「email」的屬性。讓名字匹配,它會起作用,不要忘記getter和setter。

Firebase需要類中的名稱與數據庫中的名稱匹配,以便在類的實例中轉換節點(dataSnapthot)。如果你想保留它的名字(看不出原因),有註釋。這是一個關於火力地堡和說明問題:

Firebase @PropertyName doesn't work

這個問題解釋變量必須是公開的,但設置默認情況下,我也閱讀它可以是私有的,唯一的條件是:getter和setter方法必須是註釋也是如此。也許你可以做一些實驗並讓我們知道。

相關問題