I got a big problem that I can't fix by myself, I need to put in Firebase the Likes of my social network app with the id POSTID + USERID, but actually, I don't know how to bring the postid and paste it in the likes id (post key). The main problem is about the post_key: it gives me a random id instead of the post id but honestly, I have no idea how to bring it, so the result is LIKESID = RANDOMID + USERID, instead of LIKESID = POSTID + USERID I think is very simple to fix it for an expert programmer but as a beginner, this blows my mind
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
ArrayList<Model> mList;
Context context;
public MyAdapter(Context context, ArrayList<Model> mList){
this.mList = mList;
this.context = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item , parent , false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Model model = mList.get(position);
holder.nickname.setText(model.getNickname());
holder.date.setText(model.getDate());
holder.time.setText(model.getTime());
holder.post.setText(model.getPost());
}
@Override
public int getItemCount() {
return mList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
ImageButton like;
Boolean likechecker = false;
String currentUserID;
FirebaseAuth mAuth;
TextView date, time, nickname, post, liketextview;
DatabaseReference LikesRef;
DatabaseReference Database = FirebaseDatabase.getInstance().getReference();
final String post_key = Database.push().getKey();
Integer countlikes;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
date = itemView.findViewById(R.id.date_text);
time = itemView.findViewById(R.id.time_text);
post = itemView.findViewById(R.id.post_text);
nickname = itemView.findViewById(R.id.nickname_text);
like = itemView.findViewById(R.id.like_btn);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
LikesRef = (FirebaseDatabase.getInstance().getReference().child("Likes"));
setlikebuttonstatus(post_key);
like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
likechecker = true;
LikesRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(likechecker.equals(true)){
if (snapshot.child(post_key).hasChild(currentUserID)){
LikesRef.child(post_key).child(currentUserID).removeValue();
likechecker = false;
}
else {
LikesRef.child(post_key).child(currentUserID).setValue(true);
likechecker = false;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
});
}
public void setlikebuttonstatus(final String post_key) {
post = itemView.findViewById(R.id.post_text);
liketextview = itemView.findViewById(R.id.like_textview);
LikesRef = (FirebaseDatabase.getInstance().getReference().child("Likes"));
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
LikesRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.child(post_key).hasChild(currentUserID)){
countlikes = (int) snapshot.child(post_key).getChildrenCount();
like.setImageResource(R.drawable.like);
liketextview.setText(Integer.toString(countlikes) + " Likes");}
else {
countlikes = (int) snapshot.child(post_key).getChildrenCount();
like.setImageResource(R.drawable.notlike);
liketextview.setText(Integer.toString(countlikes) + " Likes");
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
}
Homepage.Activity
package com.example.scrapbase11;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerAdapter_LifecycleAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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 com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.awt.font.TextAttribute;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.EventListener;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class HomepageActivity extends AppCompatActivity {
String currentUserID;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef, PostsRef, LikesRef;
private TextView nicknamedisplayed, displaynumblikes;
private EditText posttext;
private CircleImageView circleImageView;
private Button pubblicabtn;
private String saveCurrentdate, saveCurrenttime, tsaveCurrentdate, tsaveCurrenttime, postRandomName, nickname;
private RecyclerView recyclerView;
private FirebaseDatabase db = FirebaseDatabase.getInstance();
private DatabaseReference root = db.getReference().child("Posts");
private DatabaseReference Database = FirebaseDatabase.getInstance().getReference();
private MyAdapter adapter;
private ArrayList<Model> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
displaynumblikes = (TextView) findViewById(R.id.like_textview);
nicknamedisplayed = (TextView) findViewById(R.id.nickname_textview);
posttext = (EditText) findViewById(R.id.postedittext);
pubblicabtn = (Button) findViewById(R.id.pubblica_btn);
circleImageView = (CircleImageView) findViewById(R.id.home_profileimage);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
adapter = new MyAdapter(this, list);
recyclerView.setAdapter(adapter);
Calendar calFordDate = Calendar.getInstance();
Calendar calFordTime = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd/MM/yyyy");
saveCurrentdate = currentDate.format(calFordDate.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
saveCurrenttime = currentTime.format(calFordTime.getTime());
final String post_key = Database.push().getKey();
circleImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Sendtomyprofile();
}
});
nicknamedisplayed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Sendtomyprofile();
}
});
root.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
Model model = dataSnapshot.getValue(Model.class);
list.add(model);
}
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
UsersRef = (FirebaseDatabase.getInstance().getReference().child("Users"));
PostsRef = (FirebaseDatabase.getInstance().getReference().child("Posts"));
LikesRef = (FirebaseDatabase.getInstance().getReference().child("Likes"));
pubblicabtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Savepostmethod();
}
});
// codice per far visualizzare il proprio nickname
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
nickname = snapshot.child("nickname").getValue().toString();
nicknamedisplayed.setText("Welcome back " + nickname);
}
}
// fine del codice per visualizzare il proprio nickname
@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(HomepageActivity.this, "Database error :)", Toast.LENGTH_SHORT).show();
}
});
}
private void Sendtomyprofile() {
Intent Gotomyprofileintent =new Intent(HomepageActivity.this, ProfileActivity.class);
startActivity(Gotomyprofileintent);
}
private void Savepostmethod() {
String post = posttext.getText().toString();
if (TextUtils.isEmpty(post)) {
Toast.makeText(this, "Please write something...", Toast.LENGTH_SHORT).show();
} else {
Calendar tcalFordDate = Calendar.getInstance();
Calendar tcalFordTime = Calendar.getInstance();
SimpleDateFormat tcurrentDate = new SimpleDateFormat("ddMMyyyy");
tsaveCurrentdate = tcurrentDate.format(tcalFordDate.getTime());
SimpleDateFormat tcurrentTime = new SimpleDateFormat("HHmm");
tsaveCurrenttime = tcurrentTime.format(tcalFordTime.getTime());
postRandomName = tsaveCurrentdate + tsaveCurrenttime;
HashMap postMap = new HashMap();
postMap.put("userid", currentUserID);
postMap.put("nickname", nickname);
postMap.put("post", post);
postMap.put("time", saveCurrenttime);
postMap.put("date", saveCurrentdate);
PostsRef.child(currentUserID + postRandomName).updateChildren(postMap).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if(task.isSuccessful()) {
Toast.makeText(HomepageActivity.this, "Pubblicazione riuscita", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(HomepageActivity.this, "Pubblicazione non riuscita, controlla la tua connessione internet", Toast.LENGTH_SHORT).show();
}
}
});
}
}}
The issue is obvious. You create here:
final String post_key = Database.push().getKey();
Always a random Uid. And by using it here:
setlikebuttonstatus(post_key);
You always end up with LIKESID = RANDOMID + USERID as explained in the question. You also wrote the solution: Write the postUid
instead the random one.
What is the model here giving you back? Is it just a string?:
holder.post.setText(model.getPost());
Can you share with us how you get the list of posts
and we can find a solution. We basicaly need only the key
from each post snapshot instead of the data. You probably have it but it's not mapped for your other code to get it.
With the code from the edit you can get the post
uid like this and maybe add to the Model
class a property id
and add it afterdwards like this:
Model model = dataSnapshot.getValue(Model.class);
String key=dataSnapshot.getKey();
model.id=key;
list.add(model);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.