这是11的“建立一个社交媒体应用程序在Android工作室”教程中的一部分,我们将要在本文中介绍了以下功能:
- 我们将在博客上发表评论。
- 在这里,我们将编写评论,然后将显示评论并更新评论计数。
- 评论功能是所有博客应用程序中最好的功能。它有助于与撰写博客以及更多内容的用户进行交互。
分步实施
步骤1:创建一个新的布局资源文件
转到应用程序> res>布局>右键单击>新建>布局资源文件,并将文件命名为row_comments。以下是row_comments.xml文件的代码。
XML
Java
package com.example.socialmediaapp;
public class ModelComment {
String cId;
String comment;
String ptime;
String udp;
public String getcId() {
return cId;
}
public void setcId(String cId) {
this.cId = cId;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getPtime() {
return ptime;
}
public void setPtime(String ptime) {
this.ptime = ptime;
}
public String getUdp() {
return udp;
}
public void setUdp(String udp) {
this.udp = udp;
}
public String getUemail() {
return uemail;
}
public void setUemail(String uemail) {
this.uemail = uemail;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
String uemail;
public ModelComment() {
}
String uid;
public ModelComment(String cId, String comment, String ptime, String udp, String uemail, String uid, String uname) {
this.cId = cId;
this.comment = comment;
this.ptime = ptime;
this.udp = udp;
this.uemail = uemail;
this.uid = uid;
this.uname = uname;
}
String uname;
}
Java
package com.example.socialmediaapp;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class AdapterComment extends RecyclerView.Adapter {
Context context;
List list;
public AdapterComment(Context context, List list, String myuid, String postid) {
this.context = context;
this.list = list;
this.myuid = myuid;
this.postid = postid;
}
String myuid;
String postid;
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_comments, parent, false);
return new MyHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyHolder holder, int position) {
final String uid = list.get(position).getUid();
String name = list.get(position).getUname();
String email = list.get(position).getUemail();
String image = list.get(position).getUdp();
final String cid = list.get(position).getcId();
String comment = list.get(position).getComment();
String timestamp = list.get(position).getPtime();
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calendar.setTimeInMillis(Long.parseLong(timestamp));
String timedate = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString();
holder.name.setText(name);
holder.time.setText(timedate);
holder.comment.setText(comment);
try {
Glide.with(context).load(image).into(holder.imagea);
} catch (Exception e) {
}
}
@Override
public int getItemCount() {
return list.size();
}
class MyHolder extends RecyclerView.ViewHolder {
ImageView imagea;
TextView name, comment, time;
public MyHolder(@NonNull View itemView) {
super(itemView);
imagea = itemView.findViewById(R.id.loadcomment);
name = itemView.findViewById(R.id.commentname);
comment = itemView.findViewById(R.id.commenttext);
time = itemView.findViewById(R.id.commenttime);
}
}
}
XML
Java
package com.example.socialmediaapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
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.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
public class PostDetailsActivity extends AppCompatActivity {
String hisuid, ptime, myuid, myname, myemail, mydp, uimage, postId, plike, hisdp, hisname;
ImageView picture, image;
TextView name, time, title, description, like, tcomment;
ImageButton more;
Button likebtn, share;
LinearLayout profile;
EditText comment;
ImageButton sendb;
RecyclerView recyclerView;
List commentList;
AdapterComment adapterComment;
ImageView imagep;
boolean mlike = false;
ActionBar actionBar;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_details);
actionBar = getSupportActionBar();
actionBar.setTitle("Post Details");
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
postId = getIntent().getStringExtra("pid");
recyclerView = findViewById(R.id.recyclecomment);
picture = findViewById(R.id.pictureco);
image = findViewById(R.id.pimagetvco);
name = findViewById(R.id.unameco);
time = findViewById(R.id.utimeco);
more = findViewById(R.id.morebtn);
title = findViewById(R.id.ptitleco);
myemail = FirebaseAuth.getInstance().getCurrentUser().getEmail();
myuid = FirebaseAuth.getInstance().getCurrentUser().getUid();
description = findViewById(R.id.descriptco);
tcomment = findViewById(R.id.pcommenttv);
like = findViewById(R.id.plikebco);
likebtn = findViewById(R.id.like);
comment = findViewById(R.id.typecommet);
sendb = findViewById(R.id.sendcomment);
imagep = findViewById(R.id.commentimge);
share = findViewById(R.id.share);
profile = findViewById(R.id.profilelayout);
progressDialog = new ProgressDialog(this);
loadPostInfo();
loadUserInfo();
setLikes();
actionBar.setSubtitle("SignedInAs:" + myemail);
loadComments();
sendb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
postComment();
}
});
likebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
likepost();
}
});
like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(PostDetailsActivity.this, PostLikedByActivity.class);
intent.putExtra("pid", postId);
startActivity(intent);
}
});
}
private void loadComments() {
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
commentList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
commentList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
ModelComment modelComment = dataSnapshot1.getValue(ModelComment.class);
commentList.add(modelComment);
adapterComment = new AdapterComment(getApplicationContext(), commentList, myuid, postId);
recyclerView.setAdapter(adapterComment);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void setLikes() {
final DatabaseReference liekeref = FirebaseDatabase.getInstance().getReference().child("Likes");
liekeref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(postId).hasChild(myuid)) {
likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_liked, 0, 0, 0);
likebtn.setText("Liked");
} else {
likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like, 0, 0, 0);
likebtn.setText("Like");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void likepost() {
mlike = true;
final DatabaseReference liekeref = FirebaseDatabase.getInstance().getReference().child("Likes");
final DatabaseReference postref = FirebaseDatabase.getInstance().getReference().child("Posts");
liekeref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (mlike) {
if (dataSnapshot.child(postId).hasChild(myuid)) {
postref.child(postId).child("plike").setValue("" + (Integer.parseInt(plike) - 1));
liekeref.child(postId).child(myuid).removeValue();
mlike = false;
} else {
postref.child(postId).child("plike").setValue("" + (Integer.parseInt(plike) + 1));
liekeref.child(postId).child(myuid).setValue("Liked");
mlike = false;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void postComment() {
progressDialog.setMessage("Adding Comment");
final String commentss = comment.getText().toString().trim();
if (TextUtils.isEmpty(commentss)) {
Toast.makeText(PostDetailsActivity.this, "Empty comment", Toast.LENGTH_LONG).show();
return;
}
progressDialog.show();
String timestamp = String.valueOf(System.currentTimeMillis());
DatabaseReference datarf = FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments");
HashMap hashMap = new HashMap<>();
hashMap.put("cId", timestamp);
hashMap.put("comment", commentss);
hashMap.put("ptime", timestamp);
hashMap.put("uid", myuid);
hashMap.put("uemail", myemail);
hashMap.put("udp", mydp);
hashMap.put("uname", myname);
datarf.child(timestamp).setValue(hashMap).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(PostDetailsActivity.this, "Added", Toast.LENGTH_LONG).show();
comment.setText("");
updatecommetcount();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(PostDetailsActivity.this, "Failed", Toast.LENGTH_LONG).show();
}
});
}
boolean count = false;
private void updatecommetcount() {
count = true;
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child(postId);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (count) {
String comments = "" + dataSnapshot.child("pcomments").getValue();
int newcomment = Integer.parseInt(comments) + 1;
reference.child("pcomments").setValue("" + newcomment);
count = false;
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void loadUserInfo() {
Query myref = FirebaseDatabase.getInstance().getReference("Users");
myref.orderByChild("uid").equalTo(myuid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
myname = dataSnapshot1.child("name").getValue().toString();
mydp = dataSnapshot1.child("image").getValue().toString();
try {
Glide.with(PostDetailsActivity.this).load(mydp).into(imagep);
} catch (Exception e) {
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void loadPostInfo() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Posts");
Query query = databaseReference.orderByChild("ptime").equalTo(postId);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String ptitle = dataSnapshot1.child("title").getValue().toString();
String descriptions = dataSnapshot1.child("description").getValue().toString();
uimage = dataSnapshot1.child("uimage").getValue().toString();
hisdp = dataSnapshot1.child("udp").getValue().toString();
// hisuid = dataSnapshot1.child("uid").getValue().toString();
String uemail = dataSnapshot1.child("uemail").getValue().toString();
hisname = dataSnapshot1.child("uname").getValue().toString();
ptime = dataSnapshot1.child("ptime").getValue().toString();
plike = dataSnapshot1.child("plike").getValue().toString();
String commentcount = dataSnapshot1.child("pcomments").getValue().toString();
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calendar.setTimeInMillis(Long.parseLong(ptime));
String timedate = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString();
name.setText(hisname);
title.setText(ptitle);
description.setText(descriptions);
like.setText(plike + " Likes");
time.setText(timedate);
tcomment.setText(commentcount + " Comments");
if (uimage.equals("noImage")) {
image.setVisibility(View.GONE);
} else {
image.setVisibility(View.VISIBLE);
try {
Glide.with(PostDetailsActivity.this).load(uimage).into(image);
} catch (Exception e) {
}
}
try {
Glide.with(PostDetailsActivity.this).load(hisdp).into(picture);
} catch (Exception e) {
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return super.onSupportNavigateUp();
}
}
步骤2:创建一个新的Java类,并将该类命名为ModelComment
使用ModelComment。 Java文件。创建此活动以初始化密钥,以便我们以后可以检索密钥的值。下面是ModelComment的代码。 Java文件。
Java
package com.example.socialmediaapp;
public class ModelComment {
String cId;
String comment;
String ptime;
String udp;
public String getcId() {
return cId;
}
public void setcId(String cId) {
this.cId = cId;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getPtime() {
return ptime;
}
public void setPtime(String ptime) {
this.ptime = ptime;
}
public String getUdp() {
return udp;
}
public void setUdp(String udp) {
this.udp = udp;
}
public String getUemail() {
return uemail;
}
public void setUemail(String uemail) {
this.uemail = uemail;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
String uemail;
public ModelComment() {
}
String uid;
public ModelComment(String cId, String comment, String ptime, String udp, String uemail, String uid, String uname) {
this.cId = cId;
this.comment = comment;
this.ptime = ptime;
this.udp = udp;
this.uemail = uemail;
this.uid = uid;
this.uname = uname;
}
String uname;
}
步骤3:创建另一个新的Java类,并将该类命名为AdapterComment
使用AdapterComment。 Java文件。下面是AdapterComment的代码。 Java文件。
Java
package com.example.socialmediaapp;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class AdapterComment extends RecyclerView.Adapter {
Context context;
List list;
public AdapterComment(Context context, List list, String myuid, String postid) {
this.context = context;
this.list = list;
this.myuid = myuid;
this.postid = postid;
}
String myuid;
String postid;
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_comments, parent, false);
return new MyHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyHolder holder, int position) {
final String uid = list.get(position).getUid();
String name = list.get(position).getUname();
String email = list.get(position).getUemail();
String image = list.get(position).getUdp();
final String cid = list.get(position).getcId();
String comment = list.get(position).getComment();
String timestamp = list.get(position).getPtime();
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calendar.setTimeInMillis(Long.parseLong(timestamp));
String timedate = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString();
holder.name.setText(name);
holder.time.setText(timedate);
holder.comment.setText(comment);
try {
Glide.with(context).load(image).into(holder.imagea);
} catch (Exception e) {
}
}
@Override
public int getItemCount() {
return list.size();
}
class MyHolder extends RecyclerView.ViewHolder {
ImageView imagea;
TextView name, comment, time;
public MyHolder(@NonNull View itemView) {
super(itemView);
imagea = itemView.findViewById(R.id.loadcomment);
name = itemView.findViewById(R.id.commentname);
comment = itemView.findViewById(R.id.commenttext);
time = itemView.findViewById(R.id.commenttime);
}
}
}
第四步: 使用PostDetailsActivity活动
使用activity_postdetails.xml文件。
XML格式
使用PostDetailsActivity。 Java文件
发表评论使用此:
DatabaseReference datarf= FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments");
HashMap hashMap=new HashMap<>();
hashMap.put("cId",timestamp);
hashMap.put("comment",commentss);
hashMap.put("ptime",timestamp);
hashMap.put("uid",myuid);
hashMap.put("uemail",myemail);
hashMap.put("udp",mydp);
hashMap.put("uname",myname);
datarf.child(timestamp).setValue(hashMap);
显示像这样的评论:
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
commentList.clear();
for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
下面是PostDetailsActivity的代码。 Java文件。
Java
package com.example.socialmediaapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
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.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
public class PostDetailsActivity extends AppCompatActivity {
String hisuid, ptime, myuid, myname, myemail, mydp, uimage, postId, plike, hisdp, hisname;
ImageView picture, image;
TextView name, time, title, description, like, tcomment;
ImageButton more;
Button likebtn, share;
LinearLayout profile;
EditText comment;
ImageButton sendb;
RecyclerView recyclerView;
List commentList;
AdapterComment adapterComment;
ImageView imagep;
boolean mlike = false;
ActionBar actionBar;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_details);
actionBar = getSupportActionBar();
actionBar.setTitle("Post Details");
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
postId = getIntent().getStringExtra("pid");
recyclerView = findViewById(R.id.recyclecomment);
picture = findViewById(R.id.pictureco);
image = findViewById(R.id.pimagetvco);
name = findViewById(R.id.unameco);
time = findViewById(R.id.utimeco);
more = findViewById(R.id.morebtn);
title = findViewById(R.id.ptitleco);
myemail = FirebaseAuth.getInstance().getCurrentUser().getEmail();
myuid = FirebaseAuth.getInstance().getCurrentUser().getUid();
description = findViewById(R.id.descriptco);
tcomment = findViewById(R.id.pcommenttv);
like = findViewById(R.id.plikebco);
likebtn = findViewById(R.id.like);
comment = findViewById(R.id.typecommet);
sendb = findViewById(R.id.sendcomment);
imagep = findViewById(R.id.commentimge);
share = findViewById(R.id.share);
profile = findViewById(R.id.profilelayout);
progressDialog = new ProgressDialog(this);
loadPostInfo();
loadUserInfo();
setLikes();
actionBar.setSubtitle("SignedInAs:" + myemail);
loadComments();
sendb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
postComment();
}
});
likebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
likepost();
}
});
like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(PostDetailsActivity.this, PostLikedByActivity.class);
intent.putExtra("pid", postId);
startActivity(intent);
}
});
}
private void loadComments() {
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
commentList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
commentList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
ModelComment modelComment = dataSnapshot1.getValue(ModelComment.class);
commentList.add(modelComment);
adapterComment = new AdapterComment(getApplicationContext(), commentList, myuid, postId);
recyclerView.setAdapter(adapterComment);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void setLikes() {
final DatabaseReference liekeref = FirebaseDatabase.getInstance().getReference().child("Likes");
liekeref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(postId).hasChild(myuid)) {
likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_liked, 0, 0, 0);
likebtn.setText("Liked");
} else {
likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like, 0, 0, 0);
likebtn.setText("Like");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void likepost() {
mlike = true;
final DatabaseReference liekeref = FirebaseDatabase.getInstance().getReference().child("Likes");
final DatabaseReference postref = FirebaseDatabase.getInstance().getReference().child("Posts");
liekeref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (mlike) {
if (dataSnapshot.child(postId).hasChild(myuid)) {
postref.child(postId).child("plike").setValue("" + (Integer.parseInt(plike) - 1));
liekeref.child(postId).child(myuid).removeValue();
mlike = false;
} else {
postref.child(postId).child("plike").setValue("" + (Integer.parseInt(plike) + 1));
liekeref.child(postId).child(myuid).setValue("Liked");
mlike = false;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void postComment() {
progressDialog.setMessage("Adding Comment");
final String commentss = comment.getText().toString().trim();
if (TextUtils.isEmpty(commentss)) {
Toast.makeText(PostDetailsActivity.this, "Empty comment", Toast.LENGTH_LONG).show();
return;
}
progressDialog.show();
String timestamp = String.valueOf(System.currentTimeMillis());
DatabaseReference datarf = FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments");
HashMap hashMap = new HashMap<>();
hashMap.put("cId", timestamp);
hashMap.put("comment", commentss);
hashMap.put("ptime", timestamp);
hashMap.put("uid", myuid);
hashMap.put("uemail", myemail);
hashMap.put("udp", mydp);
hashMap.put("uname", myname);
datarf.child(timestamp).setValue(hashMap).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(PostDetailsActivity.this, "Added", Toast.LENGTH_LONG).show();
comment.setText("");
updatecommetcount();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(PostDetailsActivity.this, "Failed", Toast.LENGTH_LONG).show();
}
});
}
boolean count = false;
private void updatecommetcount() {
count = true;
final DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts").child(postId);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (count) {
String comments = "" + dataSnapshot.child("pcomments").getValue();
int newcomment = Integer.parseInt(comments) + 1;
reference.child("pcomments").setValue("" + newcomment);
count = false;
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void loadUserInfo() {
Query myref = FirebaseDatabase.getInstance().getReference("Users");
myref.orderByChild("uid").equalTo(myuid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
myname = dataSnapshot1.child("name").getValue().toString();
mydp = dataSnapshot1.child("image").getValue().toString();
try {
Glide.with(PostDetailsActivity.this).load(mydp).into(imagep);
} catch (Exception e) {
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void loadPostInfo() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Posts");
Query query = databaseReference.orderByChild("ptime").equalTo(postId);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
String ptitle = dataSnapshot1.child("title").getValue().toString();
String descriptions = dataSnapshot1.child("description").getValue().toString();
uimage = dataSnapshot1.child("uimage").getValue().toString();
hisdp = dataSnapshot1.child("udp").getValue().toString();
// hisuid = dataSnapshot1.child("uid").getValue().toString();
String uemail = dataSnapshot1.child("uemail").getValue().toString();
hisname = dataSnapshot1.child("uname").getValue().toString();
ptime = dataSnapshot1.child("ptime").getValue().toString();
plike = dataSnapshot1.child("plike").getValue().toString();
String commentcount = dataSnapshot1.child("pcomments").getValue().toString();
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calendar.setTimeInMillis(Long.parseLong(ptime));
String timedate = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString();
name.setText(hisname);
title.setText(ptitle);
description.setText(descriptions);
like.setText(plike + " Likes");
time.setText(timedate);
tcomment.setText(commentcount + " Comments");
if (uimage.equals("noImage")) {
image.setVisibility(View.GONE);
} else {
image.setVisibility(View.VISIBLE);
try {
Glide.with(PostDetailsActivity.this).load(uimage).into(image);
} catch (Exception e) {
}
}
try {
Glide.with(PostDetailsActivity.this).load(hisdp).into(picture);
} catch (Exception e) {
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return super.onSupportNavigateUp();
}
}
输出:
对于本文中使用的所有可绘制文件,请参考以下链接: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing
下面是执行这些操作后的文件结构: