# #java #android #firebase
Вопрос:
Мне удалось отобразить сообщения пользователей в моем recyclerview. Теперь я хочу открыть этот пост о другом действии, нажав. Тогда я хотел бы иметь возможность прокомментировать этот пост.
Поэтому я попытался запрограммировать эту процедуру.
Проблема в моем коде заключается в том, что, когда я пытаюсь добавить postID к действию, содержимое поста больше не отправляется в это действие, поэтому содержимое не отображается в действии. С помощью этого кода невозможно отправить идентификатор поста и содержимое поста в мою активность(см. Комментарии в коде).
Как я должен разработать код, чтобы я мог получать содержимое и идентификатор публикации?
Вот мой адаптер:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder>{
List<Post> list;
Activity context;
FirebaseFirestore firebaseFirestore;
FirebaseAuth firebaseAuth;
public PostAdapter(Activity context, List<Post> list){
this.list = list;
this.context = context;
}
public void initViews(){
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
}
@NonNull
@Override
public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.each_post, parent, false);
initViews();
return new PostViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
Post post = list.get(position);
holder.setpostContent(post.getContent());
long milliseconds = post.getTime().getTime();
String date = DateFormat.format("MM/dd/yyyy", new Date(milliseconds)).toString();
holder.setDate(date);
String userId = post.getUser();
firebaseFirestore.collection("Users").document(userId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
String user = task.getResult().getString("name");
holder.setUser(user);
}else{
Toast.makeText(context, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
//Here i tried to intent the postId to my new Activity
holder.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, OpenNewPostActivity.class);
String postId = post.PostId;
intent.putExtra("postid", postId);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class PostViewHolder extends RecyclerView.ViewHolder{
public TextView postTime, postContent, username;
View view;
public PostViewHolder(@NonNull View itemView) {
super(itemView);
view = itemView;
view.setOnClickListener(v -> openPost());
}
public void setpostContent(String content){
postContent = view.findViewById(R.id.tv_new_post_text);
postContent.setText(content);
}
public void setDate(String time){
postTime = view.findViewById(R.id.tv_new_post_time);
postTime.setText(time);
}
public void setUser(String user){
username = view.findViewById(R.id.tv_new_post_username);
username.setText(user);
}
public void getConstraintLayout(){
postLayout = view.findViewById(R.id.post_layout);
}
//Here i wanted to sent the content of the post to my new activity so i can display it on my new activity but it is not working.
public void openPost(){
int position = getAdapterPosition();
Bundle bundle = new Bundle();
bundle.putString("content", postContent.getText().toString());
bundle.putString("username", username.getText().toString());
bundle.putString("time", postTime.getText().toString());
Intent intent = new Intent(context, OpenNewPostActivity.class);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
}
И вот моя деятельность
public class OpenNewPostActivity extends AppCompatActivity {
private String postUserName, postTime, postContent;
private TextView userName, time, content;
private EditText comment;
private String postId, currentUser;
private ImageView addComment;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore firebaseFirestore;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_post);
initViews();
intiClickListener();
setPostContent();
}
private void initViews(){
userName = findViewById(R.id.tv_open_new_post_username);
time = findViewById(R.id.tv_open_new_post_time);
content = findViewById(R.id.tv_open_new_post_text);
addComment = findViewById(R.id.img_open_add_comment);
comment = findViewById(R.id.et_open_comment);
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
currentUser = firebaseAuth.getCurrentUser().getUid();
//Here i receive the post id, so i want to add the comments to the specific post.
postId = getIntent().getStringExtra("postid");
}
private void intiClickListener(){
addComment.setOnClickListener(v -> addNewComment());
}
private void setPostContent(){
// Here i replaced the content, but the textviews are not filled with the content of the post and I don't know why
Bundle bundle = getIntent().getExtras();
postUserName = bundle.getString("username");
postTime = bundle.getString("time");
postContent = bundle.getString("content");
userName.setText(postUserName);
time.setText(postTime);
content.setText(postContent);
}
private void addNewComment(){
String newComment = comment.getText().toString();
if(newComment.isEmpty()){
Toast.makeText(this, "Bitte fügen Sie ein Kommentar hinzu!", Toast.LENGTH_SHORT).show();
}
Map<String, Object> commentMap = new HashMap<>();
commentMap.put("comment", newComment);
commentMap.put("time", FieldValue.serverTimestamp());
commentMap.put("user", currentUser);
firebaseFirestore.collection("Posts/" postId "/Comments").add(commentMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
@Override
public void onComplete(@NonNull Task<DocumentReference> task) {
if(task.isSuccessful()){
Toast.makeText(OpenNewPostActivity.this, "Kommentar wird hinzugefügt!", Toast.LENGTH_SHORT).show();
comment.setText("");
}else{
Toast.makeText(OpenNewPostActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
Комментарии:
1. Что именно во всех этих строках кода работает не так, как вы ожидаете?
2. @Alex Mamo Намерение с пакетом не отправляет данные в мою активность. Это не работает, поэтому он просто отобразил несколько пустых текстовых представлений, и я не знаю, почему. Комментарии загружаются в базу данных, в этом случае проблема не в этом.
3. @Alex Mamo, возможно, так и есть, потому что у меня есть 2 списка кликов в моем классе адаптера. Значит, запущен только первый «holder.view.setOnClickListener»?
4. Скорее всего, это связано с тем, что API Firebase асинхронен. Таким образом, любой код, которому нужны данные из базы данных, должен находиться внутри метода onComplete или вызываться оттуда, верно?