OnDataChange not fire up - firebase

Hey I try to use addValueEventListener
DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Phone");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1 : snapshot.getChildren()){
if(snapshot1.getValue()==phone){
Toast.makeText(LoginActivity.this, "seeee"
, Toast.LENGTH_LONG); }
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
when I try to debug this the onDataChange method is not firing up
instead is goes out from addValueEventListener
Can anyone know how to fix this ?

Related

How to rewrite the following code since the FirebaseInstanceId() is deprecated?

The code was found from a Youtube tutorial called realtime location firebase and it's important for my Final Year Project. I appreciate all the help that i could get. Thanks in advance.
private void updateToken(FirebaseUser firebaseUser) {
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.TOKENS);
//Get Token
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
tokens.child(firebaseUser.getUid()).setValue(instanceIdResult.getToken());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void updateToken(FirebaseUser firebaseUser) {
DatabaseReference tokens = FirebaseDatabase.getInstance()
.getReference(Common.TOKENS);
FirebaseInstallations.getInstance().getId()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
tokens.child(firebaseUser.getUid())
.setValue(task.getResult());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
also try some dependencies in build.gradle(:app)
implementation platform('com.google.firebase:firebase-bom:26.8.0')
implementation 'com.google.firebase:firebase-database'

how to delete a node from firebase

I am developing an android project with firebase. and now I want to delete a node on clicking on a button. but this error occurred and I can not solve it. I want to delete the node of 1589445758397. as I press the delete button all posts in the node post start deleting one by one and then the upper node with name Posts delete. please help me to solve it.
here's my code-
private void deletePostsWithImages(final String pId, String pImage) {
////////////////////////////
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Deleting Post");
progressDialog.setMessage("Please wait...");
progressDialog.show();
/////////////////////
StorageReference picRef = FirebaseStorage.getInstance().getReferenceFromUrl(pImage);
picRef.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Query fQuery = FirebaseDatabase.getInstance().getReference("Posts")
.orderByChild("pId").equalTo(pId);
fQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
ds.getRef().removeValue();
Toast.makeText(context, "Post deleted successfully.", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(context, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void deletePostsWithoutImages(final String pId) {
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Deleting Post");
progressDialog.setMessage("Please wait...");
progressDialog.show();
Query fQuery = FirebaseDatabase.getInstance().getReference("Posts")
.orderByChild("pId").equalTo(pId);
fQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
ds.getRef().removeValue();
Toast.makeText(context, "Post deleted successfully.", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/r7nrI.png
Instead of:
for (DataSnapshot ds: dataSnapshot.getChildren()) {
ds.getRef().removeValue();
Toast.makeText(context, "Post deleted successfully.", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
try:
dataSnapshot.setValue(null);
Toast.makeText(context, "Post deleted successfully.", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
If you want to remove some specific node and you have the ID of the node then why are you listening and looping?
Just point to the node and remove it:
private void deletePostsWithoutImages(final String pId) {
.......
.......
//point to the node
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Posts").child(pId);
//remove that node
ref.removeValue();
........
}

How can I get child value with if & else condition (Firebase,SDK)

I am having trouble with my codes. What I want to do in my Login page is log as admin using email/password and when "role" is equal to admin (the other role is Guest). The admin page is MainActivity.class and the Guest page is Home.class. Can someone help me :)
And here is my code:
private void onAuthSuccess(FirebaseUser user) {
DatabaseReference ref =
FirebaseDatabase.getInstance().getReference().child("users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String role = ds.getKey();
DatabaseReference userKeyDatabase = FirebaseDatabase.getInstance().getReference().child("users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot == null) {
Toast.makeText(getApplicationContext(), "****NULLL****", Toast.LENGTH_LONG).show();
} else if(dataSnapshot.child("role").getValue().equals("Admin")) {
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
}else{
startActivity(new Intent(SignInActivity.this, Home.class));
finish();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userKeyDatabase.addListenerForSingleValueEvent(eventListener);
}}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(valueEventListener);
}
I am not sure about my code as well :(
To check role of users login you can do something like this
FirebaseDatabase firebaseDatabase=FirebaseDatabase.getInstance();
DatabaseReference db=firebaseDatabase.getReference().child("users");
db.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
if(dataSnapshot.exists()){
Log.d("user exits","usere hai");
String value =dataSnapshot.child("role").getValue().toString();
if(value.equals("Admin") && value != null){
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
}else{
startActivity(new Intent(SignInActivity.this, Home.class));
finish();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});

How to improve Flowable<Object> data reading from Firebase db using RxJava 2?

I have Recycler Viewer that displays data from Fire Base db however initial List contains around 4k elements. I am trying to show only first 15 elements instead of waiting for full list to be loaded however not sure how to do it.
I am trying to take(x) elements via Subscriber however it does not improve reading performance (it still waits for 4k elements from Firebase DB). How to speed up this?
Subscriber - Presenter
#Override
public void onBindViewHolder(final ListContentFragment.ViewHolder holder, int position) {
modelInterface.getDataFromFireBase("FinalSymbols")
.take(15)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<DataSnapshot>() {
#Override
public void accept(DataSnapshot dataFromDb) throws Exception {
//update TextView inside Recycler Viewer
holder.name.setText(dataFromDb.child(String.valueOf(holder.getAdapterPosition())).child("description").getValue().toString());
holder.description.setText(dataFromDb.child(String.valueOf(holder.getAdapterPosition())).child("categoryName").getValue().toString());
}
}
);
}
Publisher - source of Data (FireBase db)
#Override
public Flowable<DataSnapshot> getDataFromFireBase(final String childName) {
return Flowable.create(new FlowableOnSubscribe<DataSnapshot>() {
#Override
public void subscribe(final FlowableEmitter<DataSnapshot> e) throws Exception {
databaseReference.child(childName).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
e.onNext(dataSnapshot);
e.onComplete();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}, BackpressureStrategy.BUFFER);
I believe you need to use the method limitToFirst().
Something like this:
#Override
public Flowable<DataSnapshot> getDataFromFireBase(final String childName) {
return Flowable.create(new FlowableOnSubscribe<DataSnapshot>() {
#Override
public void subscribe(final FlowableEmitter<DataSnapshot> e) throws Exception {
databaseReference.child(childName).limitToFirst(15).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
e.onNext(dataSnapshot);
e.onComplete();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}, BackpressureStrategy.BUFFER);

Firebase data deleted when you delete different data with same key?

When I delete the first node "List" in Firebase, the second node "List 2" is automatically deleted. I think this is happening due to same key of child of both nodes. Is there any way to stop another node from being deleting?
Here's my code which I'm using to copy data from "List" to "List 2" and then delete the node "List". When I delete the one node the other also get deletd.
ref.child("List").child(cardTitle).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ref.child("SHOP_ITEM").child("List 2).setValue(dataSnapshot.getValue());
ref.child("SHOP_ITEM").child("List").removeValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I had the same problem, so I used a work around; I simply added a cancel value to it. Something like cancel:"true".
In your case DATABASEREF1 = List1 and DATABASEREF2 = List2..
This was what worked for me. Here is the code:
DATABASEREF1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String,String> hMdataSnapshot = (HashMap<String, String>) dataSnapshot.getValue();
hMdataSnapshot.put("canceled","true");
DATABASEREF2.setValue(hMdataSnapshot).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
DATABASEREF1.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
//DO SOMETHING
} else {
//DO SOMETHING
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//DO SOMETHING
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Resources