This is the Part 12 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article:
- We are going to view the list of users who have like a particular blog.
- After Click on total like we will be redirected to PostLikedBy.Activity.
- In that, we will be using a recycler view to show the list of users who have liked a post.
- We can also view the list of all users who likes our post from the PostDetailActivity.class.
Step By Step Implementation
Step 1: Working with the AdapterPosts.java file. Redirecting to PostLikedByActivity.class to view all the user’s list
holder.like.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(holder.itemView.getContext(), PostLikedByActivity.class); intent.putExtra("pid",pid); holder.itemView.getContext().startActivity(intent); } });
Below is the code for the AdapterPosts.java file.
Java
package com.example.socialmediaapp; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.text.format.DateFormat; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; 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 com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import java.util.Calendar; import java.util.List; import java.util.Locale; public class AdapterPosts extends RecyclerView.Adapter<com.example.socialmediaapp.AdapterPosts.MyHolder> { Context context; String myuid; private DatabaseReference liekeref, postref; boolean mprocesslike = false ; public AdapterPosts(Context context, List<ModelPost> modelPosts) { this .context = context; this .modelPosts = modelPosts; myuid = FirebaseAuth.getInstance().getCurrentUser().getUid(); liekeref = FirebaseDatabase.getInstance().getReference().child( "Likes" ); postref = FirebaseDatabase.getInstance().getReference().child( "Posts" ); } List<ModelPost> modelPosts; @NonNull @Override public MyHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.row_posts, parent, false ); return new MyHolder(view); } @Override public void onBindViewHolder( @NonNull final MyHolder holder, final int position) { final String uid = modelPosts.get(position).getUid(); String nameh = modelPosts.get(position).getUname(); final String titlee = modelPosts.get(position).getTitle(); final String descri = modelPosts.get(position).getDescription(); final String ptime = modelPosts.get(position).getPtime(); String dp = modelPosts.get(position).getUdp(); String plike = modelPosts.get(position).getPlike(); final String image = modelPosts.get(position).getUimage(); String email = modelPosts.get(position).getUemail(); String comm = modelPosts.get(position).getPcomments(); final String pid = modelPosts.get(position).getPtime(); Calendar calendar = Calendar.getInstance(Locale.ENGLISH); calendar.setTimeInMillis(Long.parseLong(ptime)); String timedate = DateFormat.format( "dd/MM/yyyy hh:mm aa" , calendar).toString(); holder.name.setText(nameh); holder.title.setText(titlee); holder.description.setText(descri); holder.time.setText(timedate); holder.like.setText(plike + " Likes" ); holder.comments.setText(comm + " Comments" ); setLikes(holder, ptime); try { Glide.with(context).load(dp).into(holder.picture); } catch (Exception e) { } holder.image.setVisibility(View.VISIBLE); try { Glide.with(context).load(image).into(holder.image); } catch (Exception e) { } holder.like.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(holder.itemView.getContext(), PostLikedByActivity. class ); intent.putExtra( "pid" , pid); holder.itemView.getContext().startActivity(intent); } }); holder.likebtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { final int plike = Integer.parseInt(modelPosts.get(position).getPlike()); mprocesslike = true ; final String postid = modelPosts.get(position).getPtime(); liekeref.addValueEventListener( new ValueEventListener() { @Override public void onDataChange( @NonNull DataSnapshot dataSnapshot) { if (mprocesslike) { if (dataSnapshot.child(postid).hasChild(myuid)) { postref.child(postid).child( "plike" ).setValue( "" + (plike - 1 )); liekeref.child(postid).child(myuid).removeValue(); mprocesslike = false ; } else { postref.child(postid).child( "plike" ).setValue( "" + (plike + 1 )); liekeref.child(postid).child(myuid).setValue( "Liked" ); mprocesslike = false ; } } } @Override public void onCancelled( @NonNull DatabaseError databaseError) { } }); } }); holder.more.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { showMoreOptions(holder.more, uid, myuid, ptime, image); } }); holder.comment.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, PostDetailsActivity. class ); intent.putExtra( "pid" , ptime); context.startActivity(intent); } }); } private void showMoreOptions(ImageButton more, String uid, String myuid, final String pid, final String image) { PopupMenu popupMenu = new PopupMenu(context, more, Gravity.END); if (uid.equals(myuid)) { popupMenu.getMenu().add(Menu.NONE, 0 , 0 , "DELETE" ); } popupMenu.setOnMenuItemClickListener( new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == 0 ) { deltewithImage(pid, image); } return false ; } }); popupMenu.show(); } private void deltewithImage( final String pid, String image) { final ProgressDialog pd = new ProgressDialog(context); pd.setMessage( "Deleting" ); StorageReference picref = FirebaseStorage.getInstance().getReferenceFromUrl(image); picref.delete().addOnSuccessListener( new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Query query = FirebaseDatabase.getInstance().getReference( "Posts" ).orderByChild( "ptime" ).equalTo(pid); query.addValueEventListener( new ValueEventListener() { @Override public void onDataChange( @NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { dataSnapshot1.getRef().removeValue(); } pd.dismiss(); Toast.makeText(context, "Deleted Successfully" , Toast.LENGTH_LONG).show(); } @Override public void onCancelled( @NonNull DatabaseError databaseError) { } }); } }).addOnFailureListener( new OnFailureListener() { @Override public void onFailure( @NonNull Exception e) { } }); } private void setLikes( final MyHolder holder, final String pid) { liekeref.addValueEventListener( new ValueEventListener() { @Override public void onDataChange( @NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.child(pid).hasChild(myuid)) { holder.likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_liked, 0 , 0 , 0 ); holder.likebtn.setText( "Liked" ); } else { holder.likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like, 0 , 0 , 0 ); holder.likebtn.setText( "Like" ); } } @Override public void onCancelled( @NonNull DatabaseError databaseError) { } }); } @Override public int getItemCount() { return modelPosts.size(); } class MyHolder extends RecyclerView.ViewHolder { ImageView picture, image; TextView name, time, title, description, like, comments; ImageButton more; Button likebtn, comment; LinearLayout profile; public MyHolder( @NonNull View itemView) { super (itemView); picture = itemView.findViewById(R.id.picturetv); image = itemView.findViewById(R.id.pimagetv); name = itemView.findViewById(R.id.unametv); time = itemView.findViewById(R.id.utimetv); more = itemView.findViewById(R.id.morebtn); title = itemView.findViewById(R.id.ptitletv); description = itemView.findViewById(R.id.descript); like = itemView.findViewById(R.id.plikeb); comments = itemView.findViewById(R.id.pcommentco); likebtn = itemView.findViewById(R.id.like); comment = itemView.findViewById(R.id.comment); profile = itemView.findViewById(R.id.profilelayout); } } } |
Step 2: Working with the PostDetailsActivity.java file. Add this line to view all users from click on total likes in PostdeatilsActivity.
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); } });
Below is the code for the PostDetailsActivity.java file.
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<ModelComment> 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<String, Object> 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<Void>() { @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(); } } |
Step 3: Working with the PostLikedByActivity Activity
Working with the activity_postlikedby.xml file
Navigate to the app > res > layout > activity_postlikedby.xml and add the below code to that file. Below is the code for the activity_postlikedby.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".PostLikedByActivity" > < androidx.recyclerview.widget.RecyclerView android:id = "@+id/likerecycle" android:layout_width = "match_parent" android:layout_height = "match_parent" app:layoutManager = "androidx.recyclerview.widget.LinearLayoutManager" tools:listitem = "@layout/row_users" /> </ RelativeLayout > |
Working with the PostLikedByActivity.java file
Go to the PostLikedByActivity.java file and refer to the following code. Below is the code for the PostLikedByActivity.java file.
Java
package com.example.socialmediaapp; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; 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.ValueEventListener; import java.util.ArrayList; import java.util.List; public class PostLikedByActivity extends AppCompatActivity { RecyclerView recyclerView; String postId; List<ModelUsers> list; AdapterUsers adapterUsers; FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_post_liked_by); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle( "Post Liked By" ); actionBar.setDisplayHomeAsUpEnabled( true ); actionBar.setDisplayShowHomeEnabled( true ); firebaseAuth = FirebaseAuth.getInstance(); actionBar.setSubtitle(firebaseAuth.getCurrentUser().getEmail()); recyclerView = findViewById(R.id.likerecycle); Intent intent = getIntent(); postId = intent.getStringExtra( "pid" ); list = new ArrayList<>(); DatabaseReference reference = FirebaseDatabase.getInstance().getReference( "Likes" ); reference.child(postId).addValueEventListener( new ValueEventListener() { @Override public void onDataChange( @NonNull DataSnapshot dataSnapshot) { list.clear(); for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { String hisUid = "" + dataSnapshot1.getRef().getKey(); getUsers(hisUid); } } @Override public void onCancelled( @NonNull DatabaseError databaseError) { } }); } private void getUsers(String hisUid) { DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference( "Users" ); databaseReference.orderByChild( "uid" ).equalTo(hisUid).addValueEventListener( new ValueEventListener() { @Override public void onDataChange( @NonNull DataSnapshot dataSnapshot) { for (DataSnapshot ds : dataSnapshot.getChildren()) { ModelUsers model = ds.getValue(ModelUsers. class ); list.add(model); } adapterUsers = new AdapterUsers(PostLikedByActivity. this , list); recyclerView.setAdapter(adapterUsers); } @Override public void onCancelled( @NonNull DatabaseError databaseError) { } }); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return super .onSupportNavigateUp(); } } |
Output:
For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing
Below is the file structure after performing these operations: