cannot access outer class variable for datasnapshot.haschild() method - android

This is my datbase tree
the below is my code to check if my database has a child with a specified number stored in num variable.
i am unable to access num variable in addListenerForSingleValueEvent
here is my code.
Thanks in advance.
mDatabase = FirebaseDatabase.getInstance().getReference();
public String nam,num;
for( contacts e : mylist)
{
num = e.getPhoneNumber();
nam = e.getName();
check(nam,num);
}
public void check(final String nam, final String num)
{
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(num)) //this line is giving error
Toast.makeText(getActivity(),num,Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(),"some error",Toast.LENGTH_SHORT).show();
}
});
}

To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference numberRef = rootRef.child(num);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Log.d("TAG", "Number exists!");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
numberRef.addListenerForSingleValueEvent(eventListener);

Related

Unable to retrieve firebase database to an android app

Problem in retrieving firebase database to an android app.
Here is the image of firebase realtime database updating from from raspberry pi
error: Failed to convert value of type java.util.HashMap to String
Below is my MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView tempvalue;
private TextView humidvalue;
private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
private DatabaseReference mRootReference = firebaseDatabase.getReference();
private DatabaseReference mChildReference = mRootReference.child("user").child("");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempvalue = (TextView)findViewById(R.id.tempvalue);
humidvalue = (TextView)findViewById(R.id.humidvalue);
}
#Override
protected void onStart() {
super.onStart();
mChildReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String Temperature = dataSnapshot.getValue(String.class);
String Humidity = dataSnapshot.getValue(String.class);
tempvalue.setText(Temperature);
humidvalue.setText(Humidity);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}}
output error while i'm running it into my phone(usb-debugging)
*
Its because you listen to null.
your database reference is like this:
mChildReference= mRootReference.child("user").child("");
this part
.child("");
is listening to a null node. Hence your error
You must add the exact path that you are trying to read.
EDIT
okay use this as the ref:
mChildReference= mRootReference.child("user");
and listen to the values like this:
mChildReference.addValueEvent(new Value......{
onDataChange(DataSnapshot datasnapshot){
String temprature= datasnapshot.child("Temprature").getValue().toString();
String humidity= datasnapshot.child("Humidity").getValue().toString();
}
})
To solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("user");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String humidity = ds.child("Humidity").getValue(String.class);
String temperature = ds.child("Temperature").getValue(String.class);
Log.d("TAG", humidity + " / " + temperature);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(valueEventListener);
It will print the humidity and temperature of all objects.
If you want to display the value of a single object, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("user").child("-L6wEaOp58bSnCGUTSMs");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String humidity = dataSnapshot.child("Humidity").getValue(String.class);
String temperature = dataSnapshot.child("Temperature").getValue(String.class);
Log.d("TAG", humidity + " / " + temperature);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(valueEventListener);

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

How i can find child in Firebase?

I have a structure of Firebase database:
DB
-User
--UID
----UsersMessages
-------uniqueID
-------textMessage
-------typeOfMessage
Code
private void takeDataFromFirebase(){
Query my_message= mRef.child(USERS_CHILD)
.orderByChild(USER_MESSAGES);
my_message.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String
{
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
But I need to get all Messages from my users. How can I get those? How I can search only childs "Messages" without "Users" and take "Message text value". Can I? How I can add this information to ListView?
To get all messages across all users, please use the following code:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messagesRef = rootRef.child(USERS_CHILD).child(uid).child("Messages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String messageText = ds.child("MessageText").getValue(String.class);
Log.d("TAG", messageText);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
messagesRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
asasddd
asasddd
asasddd
To get the messages from the users, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
DatabaseReference messagesRef = usersRef.child(userKey).child("Messages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String messageText = dSnapshot.child("MessageText").getValue(String.class);
Log.d("TAG", messageText);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
messagesRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
First, you need to get DatabaseRefence with something like:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User/...pathToMessage/Messages");
Then you can load all your messages with a callback:
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// callback to get all your messages from user.
if (dataSnapshot == null) return;
MessageModel mess = dataSnapshot.getValue(MessageModel.class);
// display message here
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

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.

get Firebase nodes by children

If I have a database that is set up like so
-users
-uId0
-Name: "Bill"
-uId1
-Name: "Bob"
-uId2
-Name: "Dave"
How do I get the uId elements if there name child starts with B.
The query should return somthing like this?
-uId0
-Name: "Bill"
-uId1
-Name: "Bob"
Thanks!!
DatabaseReference myReference = FirebaseDatabase.getInstance().getReference();
myReference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//looping all your users
for (DataSnapshot messageSnapshot:dataSnapshot.getChildren())
{
name = (String)messageSnapshot.child("Name").getValue();
if (name.toLowerCase().contains("b")) {
//u can save your name with 'b' string here
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To achieve this, please use this code:
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("users");
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String uId = (String) ds.getKey();
DatabaseReference uIdRef = FirebaseDatabase.getInstance().getReference().child("users").child(uId);
uIdRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = (String) dataSnapshot.child("Name").getValue();
if (name.matches("^[B].*$")) {
System.out.println(name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});

Categories

Resources