I got 2 same methods in one I declare string in Query and on another I declare it thru variable, but when I run apk the one I declare string inside Query works but the other does not.
First method:
private void randomtest() {
Query query = FirebaseDatabase.getInstance().getReference("users").orderByChild("username").equalTo("darkarcher5");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot users : dataSnapshot.getChildren()) {
User user = users.getValue(User.class);
Log.e("username", user.getUsername());
Log.e("password", user.getPassword());
userList.add(user);
}
txtViewPass.setText(userList.get(0).getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Second method:
private void neRandomTest() {
if (username != null) {
Query query = FirebaseDatabase.getInstance().getReference("user").orderByChild("username").equalTo(username);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot users : dataSnapshot.getChildren()) {
User user = users.getValue(User.class);
Log.e("username", user.getUsername());
Log.e("password", user.getPassword());
userList.add(user);
}
txtViewPass.setText(userList.get(0).getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Error given by second method: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
In your first method, your query is referencing on the "users" node while on your second method your query is referencing on the "user" node. If I am correct you are trying to connect to "user" node in second method which is not available in the firebase database. That's why indexoutofbounds.
Try using this:
private void neRandomTest() {
if (username != null) {
//Query query = FirebaseDatabase.getInstance().getReference("user").orderByChild("username").equalTo(username);
Query query = FirebaseDatabase.getInstance().getReference("users").orderByChild("username").equalTo(username);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot users : dataSnapshot.getChildren()) {
User user = users.getValue(User.class);
Log.e("username", user.getUsername());
Log.e("password", user.getPassword());
userList.add(user);
}
txtViewPass.setText(userList.get(0).getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Related
I have the data in firebase as given below:
I want to get the Customer and Device details for each of the Form ID. The Form IDs are generated uniquely by firebase.
I just somehow need to get access to these Form IDs.
I have set the databaseReference as follows:
databaseReference = FirebaseDatabase.getInstance().getReference("users").child(userID).child("forms");
Then I have tried the following code to retrieve the required data:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot formsSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot formIDSnapshot : formsSnapshot.getChildren()) {
Device device = formIDSnapshot.getValue(Device.class);
if (device != null) {
// get and use the data
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Update:
I am now successfully able to retrieve the form IDs, thanks to the answer by #Frank.
Now, to get the Device and Customer details I have to write the following code inside the ValueEventListener after getting the form IDs:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot formsSnapshot : dataSnapshot.getChildren()) {
String formID = formsSnapshot.getKey(); //Retrieving the formID here
//New code addition
// to get the reference to device details node
databaseReference.child(Objects.requireNonNull(formID)).child("Device details").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Device device = dataSnapshot.getValue(Device.class);
if (device != null) {
// required device details here
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
// to get the reference to customer details node
databaseReference.child(Objects.requireNonNull(formID)).child("Customer details").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Customer customer = dataSnapshot.getValue(Customer.class);
if (customer != null) {
//required customer details here
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
I understand that this is a messy code and I would like to get some cleaner approach for the same.
You can get the key of a node by calling DataSnapshot.getKey(). So to get your form IDs:
databaseReference = FirebaseDatabase.getInstance().getReference("users").child(userID).child("forms");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot formsSnapshot : dataSnapshot.getChildren()) {
String formID = formsSnapshot.getKey();
Device device = formsSnapshot.getValue(Device.class);
if (device != null) {
// get and use the data
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
There is no need for the nested loops. Simply get the children list and loop over it once. At every iteration, cast dataSnapshot to FormID class and afterwards just use its properties.
i would also suggest that you use SingleValueEventListener instead of ValueEventListener if you do not need to observe the data all the time
I have need to access a specific child from node, i have only "available key" of the specific child not complete path.
Since you know the key of the child you're looking for, you can query on that:
DatabaseReference schoolsRef = FirebaseDatabase.getInstance().getReference().child("School");
Query query = schoolsRef.orderByKey().equalTo("MZ3bW5kLJAQorgnZbYiTaOoWWSG2");
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
String email = userSnapshot.child("email").getValue(String.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
Note that you can't use orderByChild("id") as explained in my answer
here: Firebase Query Double Nested.
Just add this code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("school").child(firebaseUser.getUid();
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String email = dataSnapshot.child("Email").getValue().toString();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
try this :-
DatabaseReference mUserNameReference = FirebaseDatabase.getInstance().getReference("School").child("id").child("id");
mUserNameReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String email = dataSnapshot.child("email").getValue().toString());
//get all the key value like this
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
If you have key for that child but not complete path first get key of parent node in list like below I did.
Arraylist<String> keyList =new Arraylist();
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("school").child(firebaseUser.getUid();
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
String value= childSnapshot.getValue(String.class);
keyList.add(key);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
now use for loop or foreach loop to check if that node contains available child key.
for(String key:keyList){
DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("school").child(key).orderByChild("id").equal(availableKey);
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
Object object= childSnapshot.getValue(Object.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
hope this will help you..
I am working on an Android application. I want the first child (first UID) of the parent 'support' and store it in a String variable. How do I get the value of the first UID from the list?
I tried one approach. It doesn't work though.
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
if (dataSnapshot1.exists()) {
String futureUID = "";
for(DataSnapshot futureUIDdatasnapshot:dataSnapshot1.getChildren() ){
futureUID = futureUIDdatasnapshot.getKey();
break;
}
/*Getting the first UID from the list of UID's in queue in 'future'*/
futureUID = dataSnapshot1.getChildren().iterator().next().getKey();
/*Moving a card from 'future' to 'serving'*/
societyServiceUIDReference.child(FIREBASE_CHILD_SERVING).child(futureUID).setValue(FIREBASE_ACCEPTED);
/*Removing the UID from 'future' after it is placed in 'serving'*/
societyServiceUIDReference.child(FIREBASE_CHILD_FUTURE).child(futureUID).removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
NOTE: 'futureUID' is the UID I want
Try the following:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("support");
Query queryUid=ref.orderByKey().limitToFirst(1);
queryUid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String key=datas.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
.orderByKey().limitToFirst(n) is what does the trick. It orders the query results by key and returns only the first n results; in this case 1
mDatabase.getChild("support").orderByKey().limitToFirst(1)
.addListenerForSingleValueEvent(new ValueEventListener () {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for (DataSnapshot supportItem: dataSnapshot.getChildren()) {
String futureUID =supportItem.getKey();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Catch your error here
}
});
see Work with Lists of Data on Android
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
}
});
How can I get that value while I know nothing about the push key?
+users
+9JZTuGUzc8bx7FLrwResWmp8L583
+anon:
+email:
+fid: <- i want to get this id without knowing push key (9JZTuGUzc8bx7FLrwResWmp8L583 )
+username:
Currently, I am trying with a null response:
FirebaseDatabase.getInstance().getReference().child("users").orderByChild("anon").equalTo(getIntent().getStringExtra(EXTRA_POST_USERNAME))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user information
if(dataSnapshot.exists()){
User user = dataSnapshot.getValue(User.class);
fidanon = user.fid;}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
final Query query = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("anon").equalTo(getIntent().getStringExtra(EXTRA_POST_USERNAME));
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
final String fid = dataSnapshot.child("fid").getValue().toString();
Toast.makeText(getActivity(), fid, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Use this,will solve your problem.