I am doing a project in firebase database and wanted to delete a parent from the firebase database in a recycler view. This what it looks like from my firebase Database I want to delete this key that has an arrow.
Problem:- The code does not delete a parent key in the image. I want to delete the key with an arrow mark.
This is my code for the view-holder
public class ViewHolder1 extends RecyclerView.Adapter<ViewHolder1.ImageViewHolder> {
private Context mContext1;
private List<Model1> mModel1;
private ImageAdapter.OnItemClickListener mListener;
public ViewHolder1(Context context1, List<Model1> models1) {
mContext1 = context1;
mModel1 = models1;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext1).inflate(R.layout.row1, viewGroup, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder imageViewHolder, int i) {
final Model1 mModelcur = mModel1.get(i);
imageViewHolder.img_food.setText(mModelcur.getFood());
imageViewHolder.img_order.setText(mModelcur.getOrder());
imageViewHolder.img_cost.setText(mModelcur.getPrice());
}
#Override
public int getItemCount() {
return mModel1.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{
public TextView img_food;
public TextView img_order;
public TextView img_cost;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
img_food = itemView.findViewById(R.id.Foody);
img_order = itemView.findViewById(R.id.Ordery);
img_cost = itemView.findViewById(R.id.Costy);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if(mListener != null)
{
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION)
{
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuItem delete = menu.add(Menu.NONE, 1,1,"Delete");
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if(mListener != null)
{
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION)
{
switch(item.getItemId())
{
case 1:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener
{
void onItemClick(int position);
void onDeleteClick1(int position);
}
public void setOnItemClickListener(ImageAdapter.OnItemClickListener listener)
{
mListener = listener;
}
}
and this is for my mainactivity
mDatabaseReference2= FirebaseDatabase.getInstance().getReference("User");
mDatabaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(final DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
final String myParentNode = postSnapshot.getKey();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mDatabaseReference.orderByKey().equalTo(myParentNode).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot posts: dataSnapshot.getChildren())
{
final String key = posts.getKey();
if(key.equals(myParentNode))
{
mDatabaseReference1 = FirebaseDatabase.getInstance().getReference(key).child("Ordered");
mDatabaseReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Model1 model2=postSnapshot.getValue(Model1.class);
mModel2.add(model2);
}
mAdapter2.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onItemClick(int position) {
}
#Override
public void onDeleteClick1(int position) {
Model1 selectedItem = mModel2.get(position);
String selectedKey = selectedItem.getFood();
mDatabaseReference2= FirebaseDatabase.getInstance().getReference("User");
mDatabaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(final DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
String myKey = postSnapshot.getKey();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mDatabaseReference.orderByKey().equalTo(myKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot posts: dataSnapshot.getChildren())
{
String myKey = posts.getKey();
FirebaseDatabase.getInstance().getReference().child(myKey).child("Ordered").removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d("Delete", "Notification has been deleted");
} else {
Log.d("Delete", "Notification couldn't be deleted");
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
mDatabaseReference1.removeEventListener(mDBListener);
}
Update Can someone help me, please? The code crash after I clicked a back button now. I really need help, please. I can't seem to delete the key or the child in the recycler adapter.
Related
I have set an intent from HomeFragment Card Click to redirect to Second Activity. Also, I am sending the current position's Database ID from the recyclerView Adapter.
But in the Second Activity, only the 1st and Last items ID are received correctly. If i click on 3rd position item, then some other position's ID is send to Second Activity.
Here is my Code :
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
Context context;
List<HomeModel> homeModelList;
DatabaseReference databaseReference;
List<String> keysList;
String keyID;
public HomeAdapter(Context context, List<HomeModel> homeModelList) {
this.context = context;
this.homeModelList = homeModelList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.layout_news, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
final HomeModel homeModel = homeModelList.get(position);
holder.timesAgo.setText(homeModel.getTimesAgo().trim());
holder.newsTitleTextView.setText(homeModel.getNewsTitle().trim());
holder.newsDetailTextView.setText(homeModel.getNewsDetail().trim());
Log.e("View counts ", String.valueOf(homeModel.getViewCounts()));
holder.view_counter.setText(String.valueOf(homeModel.getViewCounts()));
Glide.with(context).load(homeModel.getNewsImage()).centerCrop().into(holder.newsThumbnailImageView);//set error and placeholder
databaseReference = FirebaseDatabase.getInstance().getReference("News");
// final String z = databaseReference.child(String.valueOf(homeModelList.get(position))).getKey();
// Toast.makeText(context, z, Toast.LENGTH_SHORT).show();
keysList = new ArrayList<>();
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Log.e("Position is ", String.valueOf(childSnapshot.getKey()));
keysList.add(childSnapshot.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pos = keysList.get(holder.getAdapterPosition());
Log.e("current Position is", pos);
Toast.makeText(context, keysList.get(position), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DetailNews.class);
intent.putExtra("currentPosition", pos);
context.startActivity(intent);
}
});
How can this Issue be Solved ? Please Guide me .
Change the following code:
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
Log.e("Position is ", String.valueOf(childSnapshot.getKey()));
keysList.add(childSnapshot.getKey());
}
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pos = keysList.get(holder.getAdapterPosition());
Log.e("current Position is", pos);
Toast.makeText(context, keysList.get(position),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DetailNews.class);
intent.putExtra("currentPosition", pos);
context.startActivity(intent);
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I can show other user post in recycler view. But i can't show my own post in that recycler view.When i open HomeFragmentActivity its showing all others post with out owners post. I am trying to see my post in this recycler view but i can't.but other user can see my post .
Anyone can help me please....
here is my code...
Post Adapter
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
public Context mContext;
private List <Post>mPost;
private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPost) {
this.mContext = mContext;
this.mPost = mPost;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(mContext).inflate(R.layout.post_item,parent,false);
return new PostAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
final Post post=mPost.get(position);
Glide.with(mContext).load(post.getPostimage()).into(holder.post_image);
if(post.getDescription().equals("")){
holder.description.setVisibility(View.GONE);
}else {
holder.description.setVisibility(View.VISIBLE);
holder.description.setText(post.getDescription());
}
publisherInfo(holder.image_profile,holder.username,holder.publisher,post.getPublisher());
isLiked(post.getPostid(),holder.like);
nrLikes(holder.likes,post.getPostid());
getComments(post.getPostid(),holder.comments);
isSaved(post.getPostid(),holder.save);
holder.image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("profileid",post.getPublisher());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.username.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("profileid",post.getPublisher());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.publisher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("profileid",post.getPublisher());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.post_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor=mContext.getSharedPreferences("PREFS",Context.MODE_PRIVATE).edit();
editor.putString("postid",post.getPostid());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new PostDetailsFragment()).commit();
}
});
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent( mContext, CommentsActivity.class);
intent.putExtra("postid",post.getPostid());
intent.putExtra("publisherid",post.getPublisher());
mContext.startActivity(intent);
}
});
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(holder.save.getTag().equals("save")){
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid()).
child(post.getPostid()).setValue(true);
}else {
FirebaseDatabase.getInstance().getReference().child("Saves").child(firebaseUser.getUid()).
child(post.getPostid()).removeValue();
}
}
});
holder.comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent( mContext, CommentsActivity.class);
intent.putExtra("postid",post.getPostid());
intent.putExtra("publisherid",post.getPublisher());
mContext.startActivity(intent);
}
});
holder.likes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext, FollowersActivity.class);
intent .putExtra("id",post.getPostid());
intent.putExtra("title","likes");
mContext. startActivity(intent);
}
});
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.like.getTag().equals("like")){
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid()).child(firebaseUser.getUid()).setValue(true);
addNotifications(post.getPublisher(),post.getPostid());
}else {
FirebaseDatabase.getInstance().getReference().child("Likes").child(post.getPostid()).child(firebaseUser.getUid()).removeValue();
}
}
});
}
#Override
public int getItemCount() {
return mPost.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image_profile,post_image,like,comment,save;
public TextView username,likes,comments, description,publisher;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image_profile=itemView.findViewById(R.id.image_profile);
post_image=itemView.findViewById(R.id.post_image);
like=itemView.findViewById(R.id.like);
comment=itemView.findViewById(R.id.comment);
save=itemView.findViewById(R.id.save);
username=itemView.findViewById(R.id.username);
likes=itemView.findViewById(R.id.likes);
comments=itemView.findViewById(R.id.comments);
description=itemView.findViewById(R.id.description);
publisher=itemView.findViewById(R.id.publisher);
}
}
private void getComments(String postid, final TextView comments){
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Comments").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
comments.setText("View All"+dataSnapshot.getChildrenCount()+"Comments");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void isLiked(String postid, final ImageView imageView){
final FirebaseUser firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(firebaseUser.getUid()).exists()){
imageView.setImageResource(R.drawable.ic_liked);
imageView.setTag("liked");
}
else{
imageView.setImageResource(R.drawable.ic_like);
imageView.setTag("like");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void addNotifications(String userid, String postid){
DatabaseReference reference=FirebaseDatabase.getInstance().getReference("Notifications").child(userid);
HashMap<String,Object>hashMap=new HashMap<>();
hashMap.put("userid",firebaseUser.getUid());
hashMap.put("text","liked your post");
hashMap.put("postid",postid);
hashMap.put("ispost",true);
reference.push().setValue(hashMap);
}
private void nrLikes(final TextView likes, String postid){
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Likes").child(postid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
likes.setText(dataSnapshot.getChildrenCount()+" likes");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void publisherInfo (final ImageView image_profile, final TextView username, final TextView publisher, final String userId ){
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Users").child(userId);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user=dataSnapshot.getValue(User.class);
Glide.with(mContext).load(user.getImageurl()).into(image_profile);
username.setText(user.getUsername());
publisher.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void isSaved(final String postId, final ImageView imageView){
FirebaseUser firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Saves").
child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(postId).exists()){
imageView.setImageResource(R.drawable.ic_save_black);
imageView.setTag("saved");
}else {
imageView.setImageResource(R.drawable.ic_save);
imageView.setTag("save");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Home Fragment
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private PostAdapter postAdapter;
private List<Post>postLists;
private List<String> followinglist;
ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_home, container, false);
progressBar=view.findViewById(R.id.progress_circular);
recyclerView=view.findViewById(R.id.recyler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
postLists=new ArrayList<>();
postAdapter=new PostAdapter(getContext(),postLists);
recyclerView.setAdapter(postAdapter);
checkFollowing();
return view;
}
private void checkFollowing(){
//
followinglist=new ArrayList<>();
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Follow").
child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followinglist.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
followinglist.add(snapshot.getKey());
}
readPosts();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void readPosts(){
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("posts");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postLists.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Post post=snapshot.getValue(Post.class);
for(String id : followinglist){
if(post.getPublisher().equals(id)){
postLists.add(post);
}
}
}
postAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Remove the
For (String Id : following list)
And let the codes
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private PostAdapter postAdapter;
private List<Post>postLists;
private List<String> followinglist;
ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_home, container, false);
progressBar=view.findViewById(R.id.progress_circular);
recyclerView=view.findViewById(R.id.recyler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
postLists=new ArrayList<>();
postAdapter=new PostAdapter(getContext(),postLists);
recyclerView.setAdapter(postAdapter);
checkFollowing();
return view;
}
private void checkFollowing(){
//
followinglist=new ArrayList<>();
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Follow").
child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followinglist.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
followinglist.add(snapshot.getKey());
}
readPosts();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void readPosts(){
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("posts");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postLists.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Post post=snapshot.getValue(Post.class);
{
postLists.add(post);
}
It will show all post each 1 time
Add all post's to the list
for(String id : followinglist){
postLists.add(post);
}
I would like to know how can I do a recyclerView that shows data that I got from this database reference:
Salas= new ArrayList<String>();
DatabaseReference referenceSalas = FirebaseDatabase.getInstance().getReference("salas/");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("usuarios/");
FirebaseAuth autenticacao = FirebaseAuth.getInstance();
String emailUsu = autenticacao.getCurrentUser().getEmail();
reference.orderByChild("email").equalTo(emailUsu).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
nomeProf = datas.child("nome").getValue().toString();
referenceSalas.orderByChild("nomeProf").equalTo(nomeProf).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
Salas.add(datas.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
I tried to do the RecyclerView like this:
public class salasFragment extends Fragment {
private RecyclerView mRecycleViewSalas;
private adapterSalas adapterSalas;
private ArrayList<salas> listaSalas= new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private TextView txtSalas, txtTeste;
private String nomeProf;
private String teste="", piru;
private DatabaseReference reference = FirebaseDatabase.getInstance().getReference("usuarios/");
private DatabaseReference referenceSalas = FirebaseDatabase.getInstance().getReference("salas/");
private ValueEventListener valueEventListenerSalas;
ArrayList<String> salasAula = new ArrayList<String>();
public salasFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_salas, container, false);
final Context context = view.getContext();
txtSalas= view.findViewById(R.id.txtSalas);
txtTeste= view.findViewById(R.id.txtTeste);
mRecycleViewSalas= view.findViewById(R.id.recyclerSalas);
adapterSalas= new adapterSalas(listaSalas, context);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
mRecycleViewSalas.setLayoutManager(layoutManager);
mRecycleViewSalas.setHasFixedSize(true);
mRecycleViewSalas.setAdapter(adapterSalas);
return view; }
#Override
public void onStart() {
super.onStart();
recuperarSalas();
}
#Override
public void onStop() {
super.onStop();
reference.removeEventListener(valueEventListenerSalas);
}
public void recuperarSalas(){
FirebaseAuth autenticacao = FirebaseAuth.getInstance();
String emailUsu = autenticacao.getCurrentUser().getEmail();
valueEventListenerSalas = reference.orderByChild("email").equalTo(emailUsu).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
nomeProf = datas.child("nome").getValue().toString();
referenceSalas.orderByChild("nomeProf").equalTo(nomeProf).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
salas salas=datas.getKey(salas.class);
listaSalas.add(salas);
}
adapterSalas.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
my adapter:
public class adapterSalas extends RecyclerView.Adapter<adapterSalas.myViewHolder> {
private List<salas> Salas;
private Context context;
public adapterSalas(List<salas> listaSalas, Context c ) {
this.Salas= listaSalas;
this.context = c;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View itemLista = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_salas, parent, false);
return new myViewHolder(itemLista);
}
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
salas sala = Salas.get(position);
holder.btn1.setText(sala.getPrimeiro());
}
#Override
public int getItemCount() {
return Salas.size();
}
public class myViewHolder extends RecyclerView.ViewHolder{
Button btn1;
public myViewHolder(#NonNull View itemView) {
super(itemView);
btn1 = itemView.findViewById(R.id.btn1);
}
}
}
Although this line "salas salas=datas.getKey(salas.class);" does not work properly when I use "getKey", It only works when "getValue" is used. There is no way of me doing this project with "getValue" instead of "getKey". So there is any way that can make this recyclerView works properly with "getKey" ?
Have you got the data from the firebase already?
If you got the data in an arraylist already, simply plug it in an adapter (you will need to create a RecyclerView adapter, a class to describe the value of each RecyclerView items) and set it to the RecyclerView and you are good to go!
You can use FirebasRecyclerAdapter as you recyclerView adapter. check out this link for a guide on how to use it.
https://medium.com/android-grid/how-to-use-firebaserecycleradpater-with-latest-firebase-dependencies-in-android-aff7a33adb8b
I have implemented a search function on my application and it displays the results however the results can not be clicked. When not in search the onClick method works fine. Here is the code for my main class where the search takes place
MainActivity.java
public class MainActivity extends AppCompatActivity implements
RecyclerViewAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<Buildings> mUploads;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private FirebaseStorage mStorage;
private ValueEventListener mDBListener;
private EditText msearch;
ArrayList<Buildings> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUploads = new ArrayList<>();
mStorage = FirebaseStorage.getInstance();
mDatabaseRef =
FirebaseDatabase.getInstance().getReference("Buildings");
mAdapter = new RecyclerViewAdapter(MainActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(MainActivity.this);
msearch = findViewById(R.id.search);
arrayList = new ArrayList<>();
msearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int
count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().isEmpty())
{
search(s.toString());
}
else{
search("");
}
}
});
//GET DATA FROM FIREBASE!!
mDBListener = mDatabaseRef.addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUploads.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Buildings upload = postSnapshot.getValue(Buildings.class);
upload.setKey(postSnapshot.getKey());
mUploads.add(upload);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MainActivity.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
} //end of on create
private void search(String s) {
Query query = mDatabaseRef.orderByChild("name")
.startAt(s).endAt(s + "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onItemClick(int position) {
Buildings selectedItem = mUploads.get(position);
final String name = selectedItem.getName();
final String address = selectedItem.getAddress();
final String image_url = selectedItem.getImage_url();
final double longt = selectedItem.getLongitude();
final double lat = selectedItem.getLatitude();
final String uid = selectedItem.getUserID();
final String desc = selectedItem.getDescription();
final String categ = selectedItem.getCategorie();
Intent mainIntent = new Intent(MainActivity.this, ProfileActivity2.class);
mainIntent.putExtra("b_name", name);
mainIntent.putExtra("b_address", address);
mainIntent.putExtra("b_image_url", image_url);
mainIntent.putExtra("b_userId", uid);
mainIntent.putExtra("b_desc", desc);
mainIntent.putExtra("b_categ", categ);
Bundle b = new Bundle();
b.putDouble("longt", longt);
b.putDouble("lat", lat);
mainIntent.putExtras(b);
startActivity(mainIntent);
finish();
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ImageViewHolder> {
private Context mContext;
private List<Buildings> mUploads;
private OnItemClickListener mListener;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private boolean checkUid;
public RecyclerViewAdapter(Context context, List<Buildings> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.buildings_row_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Buildings uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
holder.textViewAddress.setText(uploadCurrent.getAddress());
Glide.with(mContext).load(mUploads.get(position).getImage_url()).into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public TextView textViewAddress;
LinearLayout view_container;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.building_name);
imageView = itemView.findViewById(R.id.thumbnail);
view_container = itemView.findViewById(R.id.container);
textViewAddress = itemView.findViewById(R.id.address);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if(checkUid =true && mCurrentUser != null){
MenuItem delete = menu.add(Menu.NONE, 1, 1, "Delete");
delete.setOnMenuItemClickListener(this);
}
else{
//do nothing
}
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
}
Should I be adding something to my search function?
You are creating new adapter on reponse of your query, which isn't having active interface attached. So instead of creating new adapter, just update the data list and notify adapter.
Refer below code.
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
// Remove below two lines,
// It is not needed as we only need to notify adapter about the data change.
// RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
// mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
In search method, you create a new adapter but not setting its onItemClickListener.
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
Separate the setData and construct method for adapter, then you don't need to create new adapter every search. Or just set mAdapter.setOnItemClickListener for it.
I have implemented a notification center using a
recyclerview displayed on a fragment , when I click on the item it writes a value on the database and then base of the condition the green Notification Bell appears/dissapears, the problem here is that all items get affected from trembling effect
Image:
https://im4.ezgif.com/tmp/ezgif-4-1adb4a5b29e3.gif
My adapter
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position) {
NotifsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(currentUserID).child("comments").child(delUid).hasChild("state"))
{
String state = dataSnapshot.child(currentUserID).child("comments").child(delUid).child("state").getValue().toString();
if (state.equals("unread"))
{
holder.notifImg.setVisibility(View.VISIBLE);
}
else {
holder.notifImg.setVisibility(View.GONE);
}}}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{ NotifsRef.child(currentUserID).child("comments").child(delUid).child("state").setValue("read");
}
});
}
#Override
public int getItemCount() {
return mNotifications.size();
}
Fragment:
{
OnCreate{...}
notificationList = (RecyclerView) notificationFragmentView.findViewById(R.id.notifications_list);
notificationAdapter = new NotificationAdapter(getContext(), mNotifications);
notificationList.setAdapter(notificationAdapter);
notificationList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
notificationList.setLayoutManager(linearLayoutManager);
}
private void readMsgList()
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{ mNotifications.clear();
for (DataSnapshot snapshot : dataSnapshot.child(currentUserID).child("comments").getChildren())
{
Notifications notifications = snapshot.getValue(Notifications.class);
mNotifications.add(notifications);
}
notificationAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}});
}
I have tried to change the listener from ValueEventListener to SingleValueEventListener but without any result.
Is there any way to correct this ?