How do I retrieve a specific information on firebase database? - android

I am new to android programming and wish to explore more on Android programming. My current database tree looks like this and this is how I push the data into the database .
Can any professional teach me on how to retrieve a specific data (e.g. name / phone number) from a specific user in the user list and display them?
Thanks in advance!
Update:
After trying several solutions, the only code that can retrieve the name is this
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child("-MA5f3qb0nBBTkViv-pz");
I even tried to assign the UID to a string and put in into the second child like this
String UID = firebaseAuth.getCurrentUser().getUid();
But the code will not run too with the error of "Attempt to invoke virtual method on a null object reference".

To retrieve information try the following:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("User");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User userInfo = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Add a reference to node User and then using addListenerForSingleValueEvent you can retrieve the values.

Related

Firebase and recyclerView

Hi I'm new in firebase and android studio and I have a problem
I want to store the data of this database in an array and next use the array to make a recycler view
Then in the main activity I wrote this:
And if I run the app only this is shown:
But if I do the same but instead of firebase i use a String[] with the data i want to show it works but i don't know why with firebase i can't.
if I change the references by this:
reference = database.getReference(FirebaseReferences.POKEMONS_REFERENCES);
reference.child(FirebaseReferences.APP_REFERENCES).addValueEventListener(new ValueEventListener() {
when I run the app, it automatically closes and i don't know what to do.
Could you please tell me what i'm doing wrong?
Thank you in advance.
Here is the logCat
https://github.com/adcasna/SearchViewPrueba2/wiki
Fisrts of all, please note that the Firebase documentation recommends against using arrays. Using an array is an anti-pattern when it comes to Firebase. One of the many reasons Firebase recommends against using arrays is that it makes the security rules impossible to write. If you still want to use this kind of structure, for getting those names and store them in an ArrayList, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference appRef = rootRef.child("pokemons").child("app");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String c_name = ds.child("c_name").getValue(String.class);
list.add(c_name);
Log.d("TAG", c_name);
}
Log.d("TAG", list );
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
appRef.addListenerForSingleValueEvent(eventListener);

Firebase get the value of the data Android

String userID = user.getUid();
mFirebaseDatabase = FirebaseDatabase.getInstance();
I have userId of the user so when I'm opening my app for the 2nd time(after signing in) I should not show the select user type layout. So I ve to check whether the use is Customer or Staff internally. So the problem is I ve to check the User Id is there . I couldn't find any method to get whether user Id is there or not! There is method called addListenerForSingleValueEvent but that won't help me in my scenario. Pic of the database is given here
I don't know how to continue after this
mFirebaseDatabase.getReference().child("Users").child("Customers")
To check if an user exists in a particular section of your Firebase database, first you need to add a listener and then use exists() method directly on the dataSnapshot object. So, asumming that Users node is a direct child of the Firebase-database root, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference customersRef = rootRef.child("Users").child("Customers").child(userID);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//do somethig
} else {
//do something else
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
customersRef.addListenerForSingleValueEvent(eventListener);

I can't get the key of firebase database

In my solution I save data from Windows form application. There is no problem. I can list them in my android app. On this point I am trying to get key value to update the data, but always I get null.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myReference = database.getReference();
Query myTopPostsQuery = myReference.child("DURUSLAR").orderByChild("kayitid").equalTo("1298843637");
myTopPostsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
{
//Childadi =postSnapshot.getKey().toString();
String anahtar=postSnapshot.getKey().toString();
Toast.makeText(getApplicationContext(),anahtar,Toast.LENGTH_LONG);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Can you please help me?
When you execute a query at a location in the Firebase Database, it will search for the property you order/filter on in each child under that location. Since you query in /DURUSLAR, Firebase looks for /DURUSLAR/{something}/kayitid. Such a property does not exist, since you only have /DURUSLAR/{something}/{pushid}/kayitid.
To fix this problem you have two options:
query at a lower level
query to the property at its (fixed) path
The first option is to create the query at a lower level in the tree:
Query myTopPostsQuery = myReference.child("DURUSLAR/K6").orderByChild("kayitid").equalTo("1298843637");
Now the query is looking for /DURUSLAR/{pushid}/kayitid and it will work.
The second option is to query for the known path of the property:
Query myTopPostsQuery = myReference.child("DURUSLAR").orderByChild("K6/-KknsAR4_KFAeZ1HVXPW/kayitid").equalTo("1298843637");
It seems unlikely you want this here, but the approach may be helpful in other situations. Often when you need this approach with push IDs in the path, you'll want to look at http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value.
The reason you are getting null is because you are doing orderByChild on the wrong level of data . According to your data u need to have a child K4-> which has a unique_id_push_id -> kayitid.Therefore you need to traverse the K4 in order to get 1298843637 for key kayitid.You can follow this tutorial to understand the retrieving of data from firebase .
Query myTopPostsQuery = myReference.child("DURUSLAR").child("k6").orderByChild("kayitid").equalTo("1298843637");
myTopPostsQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
{
//Childadi =postSnapshot.getKey().toString();
String anahtar=postSnapshot.getKey().toString();
Toast.makeText(getApplicationContext(),anahtar,Toast.LENGTH_LONG);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to search for a values of Child in firebase Android

DatabaseReference databaseReference=mDatabase;
String queryText="Hotel";
databaseReference.orderByChild("Coupon")
.startAt(queryText)
.endAt(queryText+"\uf8ff");
Here I attached the code which I used to get child names of "Coupon" when I entered the "Hotel" query under the Coupon.But I got blank.I supposed to get Hotel1,Hotel2 object.I'm new to firebase.So hope your support .Thanks in advance.
In the Web version, they use something called ElasticSearch, you could try to read more here: https://firebase.googleblog.com/2014/01/queries-part-2-advanced-searches-with.html
But for Android, I think there isn't any functionality to perform a search like that. What I would do is to query all the records then filter them myself:
DatabaseReference databaseReference = mDatabase;
mDatabase.addValueEventListener(new ValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot val : dataSnapshot.getChildren()){
//I am not sure what record are you specifically looking for
//This is if you are getting the Key which is the record ID for your Coupon Object
if(val.getKey().contains("Hotel")){
//Do what you want with the record
}
//This is if your are querying for the hotel child
if(val.child("hotel").getValue(String.class).contains("Hotel")){
//Do what you want with the record
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
}
Don't load your whole database to filter out needed data. It produces unnecessary traffic which has to be loaded, calculated and deleted. Instead, use:
DatabaseReference myRef = FirebaseDatabase.getDatabaseReference();
Query searchQuery = myRef.child("Coupon").orderByChild("hotel").equalTo("yourSearchString");
To make this code work, you also have to add indexOn on your corresponding attribute in the rules (of Firebase Database console).

FireBase Android Need 1 value saved under a single user

I have the following data structure on firebase for the user MF0qeRA4p7djfjgXxqwFOck3m6p02. I want to get the value of item3 to populate a single field into the User interface on an Android App. I have been looking through samples on Stackoverflow, but all I have found are outdated and do not work with the current version of firebase. I'm new to firebase completely and this is my first app on android. I've got the oncreate user method to populate the users email address and add the 4 item fields, but retrieving the data I'm completely lost and I am not sure where to even begin.
-Users
---MF0qeRA4p7djfjgXxqwFOck3m6p02
------item1:"1"
------item2:"2"
------item3:"3"
------item4:"4"
According to what I can identify is, you are facing problem retrieving data from this reference. Here is the code:
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.child("MF0qeRA4p7djfjgXxqwFOck3m6p02").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> map=(Map<String, Object>)dataSnapshot.getValue();
String item3=(String)map.get("item3");
display(item3);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope this helps.
You can create a custom model and inside you can insert elements. Something like this:
public class Item {
private List<Object> ojects;
}
There you can save instance of Item on database. In this case you have more controll. Other case is to use push() method, that will generate a new encoded key, something like this:
mDatabase.child("items").push().put(new Object());

Categories

Resources