How do I modify real-time DB change to firestore code? - android

How do I modify the Realtime Database change to Firestore code?
Now, I am using this code to realize my function in real-time
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Saves").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
progressDialog.dismiss();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
mySaves.add(snapshot.getKey());
}
readSaves();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
private void readSaves() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
progressDialog.dismiss();
postList_saves.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
PostModel postModel = snapshot.getValue(PostModel.class);
for(String id : mySaves){
if(postModel.getPostid().equals(id)){
postList_saves.add(postModel);
}
}
}
myFotoAdapter_saves.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
my DB structure
I tried to modify this code
CollectionReference ref = db.collection("Saves");
ref.addSnapshotListener(this, new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException error) {
if(error != null){
return;
}
for(DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()){
DocumentSnapshot documentSnapshot = dc.getDocument();
mySaves.add(documentSnapshot.getKey());
}
readSaves();
}
});
private void readSaves() {
db.collection("Posts").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if(!queryDocumentSnapshots.isEmpty()){
progressDialog.dismiss();
postList_saves.clear();
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list){
PostModel post = d.toObject(PostModel.class);
postList_saves.add(post);
}
myFotoAdapter_saves.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), getApplicationContext().getResources().getString(R.string.noData), Toast.LENGTH_SHORT).show();
}
}
});
}
But, it's has error error: cannot find symbol mySaves.add(documentSnapshot.getKey());
and cannot filter the data, I got all the posts not saved date.
I think I am not getting the key values.
How do I modify the code?

Related

How to delete specific number of nodes from firebase realtime database

I have an app which has a structure like
Chatrooms--------
Messages-------
Chatroomid---------
-Message1
-Message2
In this chatroom when the number of messages reaches 200 I want to delete the first 50 messages.So if the messages are 200 it will delete the messages from message1 to message50.I am using a push key for the messages.
My java code for sending message
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Map<String,Object> message = new HashMap<>();
message.put("message",messageBox.getText().toString());
message.put("imageurl",ppurl);
message.put("sender",FirebaseAuth.getInstance().getCurrentUser().getUid());
reference2.push().setValue(message).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
messageBox.setText("");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(chatroom.this, "Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
My java code for retrieving message
private void getdata() {
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
for (DataSnapshot npsnapshot : snapshot.getChildren()) {
message l = npsnapshot.getValue(message.class);
list.add(l);
}
messageAdapter.notifyDataSetChanged();
}else {
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
You can easily add this in your existing getdata function:
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
if (snapshot.getChildrenCount() > 200) {
int count = 0;
Map<String, Object> updates = new HashMap<>();
for (DataSnapshot npsnapshot : snapshot.getChildren()) {
if (count++ <= 50) {
updates.put(npsnapshot.getKey(), null);
}
}
ref.updateChildren(updates); // this will refire onDataChange, so we'll update the UI then
}
else {
for (DataSnapshot npsnapshot : snapshot.getChildren()) {
message l = npsnapshot.getValue(message.class);
list.add(l);
}
messageAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // don't ignore errors
}
});
There is also a Cloud Functions sample that can do this server-side for you btw: https://github.com/firebase/functions-samples/tree/master/limit-children

use two different adapters - android -fragment

I have an if and else block. if it conforms to the if condition, it will list the data in the database as imageAdapter. anasayfaAdapter will be used if elsee comes into it.
if(kisiIdd.equals(userId))
{
adapterr = new imageAdapter(getActivity(), kullaniciList);
recyclerView.setAdapter(adapterr);
adapterr.setOnItemClickListener(urunlerimFragment.this);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
kullaniciList.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Kullanici kullaniciModel = postSnapshot.getValue(Kullanici.class);
String id=kullaniciModel.getKisiId().toString();
kullaniciList.add(kullaniciModel);
kullaniciModel.setKey(postSnapshot.getKey());
}
adapterr.notifyDataSetChanged();
progressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
progressCircle.setVisibility(View.INVISIBLE);
}
});
}
else
{
anasayfaAdapter = new anasayfaAdapter(getActivity(), kullaniciList);
recyclerView.setAdapter(anasayfaAdapter);
anasayfaAdapter.setOnItemClickListener(urunlerimFragment.this);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
kullaniciList.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Kullanici kullaniciModel = postSnapshot.getValue(Kullanici.class);
String id=kullaniciModel.getKisiId().toString();
kullaniciList.add(kullaniciModel);
kullaniciModel.setKey(postSnapshot.getKey());
}
anasayfaAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
if the data in the database from the database if the imageAdapter to use to list. In the Else block, it will use the anasayfaAdapter adapter. Why would an algorithm fit?
but it does not happen. How do you have a suggestion?

how i get all data from firebase realtime database

I have a database with this schema:
I tested this code but I can't get any msg from the database. I would appreciate your help.
private void Add_Chat(final DataSnapshot dataSnapshot) {
root.child("ChatSpace").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String nom=dataSnapshot.child("ChatSpace").child("msg").getValue(String.class);
System.out.println(nom); //prints "Do you have data? You'll love Firebase."
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Assuming that ChatSpace is a direct chlid of your Firebase database root, to get all messages please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference chatSpaceRef = rootRef.child("ChatSpace");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String msg = ds.child("msg").getValue(String.class);
Log.d("TAG", msg);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
chatSpaceRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
bbbName
bbbName
Name

Firebase Query get values

I have a list of Child-Data and wants to have a certain value.
My Firebase structure:
Now, I only have the Child "Text" and the currendUser "0zwtyRwgnogC8Qk91AtHj7amZb63"
So how can I get the values of "text and "user_id"?
My source code:
mDatabaseText = FirebaseDatabase.getInstance().getReference().child("Text");
query = mDatabaseText.startAt(mCurrentUser.getUid());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot textSnapshot : dataSnapshot.getChildren()) {
/* String text = textSnapshot.getKey();
Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show(); */
TextModel textModel = chatSnapshot.getValue(TextModel.class);
String t = textModel.getText();
Log.i("!!!!!!!text", t);
Toast.makeText(getActivity(), t, Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
But this code doesn't work, why?
I used the query startAt.
Please use this code:
FirebaseDatabase rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference currentUserIdRef = rootRef.child("Text").child(currentUserId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = (String) ds.getKey();
DatabaseReference userIdRef = rootRef.child("Text").child(currentUserId).child(userId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String user_id = (String) dataSnapshot.child("user_id").getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
};
userIdRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
};
currentUserIdRef.addListenerForSingleValueEvent(eventListener);
In which currentUserId is the variable that you say you already have it.
Hope it helps.

Firebase query in query

I am trying to make multiple queries to my Firebase database, but it seems I am doing something wrong, and I just can't seem to understand what.
My code is this:
database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("Tbl1");
Query tbl1Query = ref.orderByChild("type");
tbl1Query .addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
Tbl1Item item = singleSnapshot.getValue(Tbl1Item .class);
tbl1List.add(item);
}
DatabaseReference ref = database.child("Tbl2");
Query tbl2Query = ref.orderByChild("status");
tbl2Query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
tbl2Item item = singleSnapshot.getValue(tbl2Item.class);
tbl2List.add(item);
}
DatabaseReference ref = database.child("Tbl3");
Query tbl3Query = ref.orderByChild("status");
tbl3Query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
tbl3item item = singleSnapshot.getValue(tbl3item.class);
tbl3List.add(item);
}
SortTableData();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The problem is that the app crashes though I get no error in console.
What I am trying to obtain, is create 3 lists of objects with data from table1, table2 and table3 and then call a method that will process that data.
If I remove the 2nd and 3rd queries, everything works fine, but I don't have all the needed data... so what I am doing wrong?

Categories

Resources