Reading Data using a ValueEventListener - Android Firebase
Vložit
- čas přidán 8. 02. 2017
- Reading Data using a ValueEventListener - Android Firebase
In this video I show you how to read data from a Firebase Database. There are many ways you DON’T want to get the data. The JSON format can get a little tricky (at least I think so). I hope this video helps you and saves you a little bit of time.
Firebase features:
-Store Real-Time data
-Set up users with various logins from Facebook, Email, Twitter, Google, Github etc..
-Use Cloud Messenging
-Image and Video Storage
-Web Hosting
-Push Notifications,
-Google AdWords
And MORE!
Honestly I think Firebase is pretty amazing. It's just yet another great product from google. It's very easy to use and has so much functionality.
Watch my videos and learn how to use Firebase FREE!
➤Source Code:
↻github.com/mitchtabian/Fireba...
➤Firebase Tutorial Playlist:
↻ goo.gl/T9Wp2f
➤Firebase Link:
↻ firebase.google.com/
➤My Keyboard:
↻ goo.gl/1RUqgb
➤My Microphone:
↻ goo.gl/mPh3dk
➤Check out our website:
↻ www.CodingWithMitch.com
This is the only place where i got proper and details explanation for reading data functionality. Thanks!!
Thx for lifting my confusion with the ondatachange!
Thank you so much for this tutorial. It helped me very much! :)
4:25 what explanation I was looking for... Thanks.
who calls this on change when it's just the basic read -.-
Finally...I was able to read the data. I have watch so many videos, all the same, but not as specific as your. great Video!
The getter and setter made a difference. I didn't used the array list but instead, I used .setText(uInfo.getName()) to show it.
Thank you so much for this video! If possible, add in the description how to assign a global variable using Async Firebase EventListeners, because that was what I was searching for and I saw a lot of unanswered questions on SO using the same keywords. I only found your video by chance!
Thank your so much ! your tutorial give me a new knowledge for the future !
Good Tutorial Best One ! excellent work
Thank you! 4:38 saved my day.
great, good job mitch.
thanks for helpfull tutorial , this what im searcing...
Thank you so much for making this playlist! You helped me a lot :)
Can you please explain how the userID for the current logged in account can iterate over the different uniqueID objects??
Could you make more tutorials like this? Can you make a tutorial how to get a nested json data structure from firebase into Android app?
Thanks, helped a lot!
nice video man well explained
How do I pull the data like this but into a already created GUI? Is there any way I can move the result data? Or do I just call them into empty variables that are already positioned?
Great tutorial, but can help what changes needs to be made if I want to use a custom listview?
can I just read 1 from those 3 data?
for example, I just want display "Name"
I don't have any errors, but still the data is not shown in my activity. What can be the problem? Dependencies or not UI for firebase?
I have used your code. email is being retrieved from Authentication console but the "name" is not getting retrieved from the database.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
what should i do im getting this error data is not getting fetched
have you fixed it ,same error here
add your database entries as "entry_name" instead of just writing entry name. add them as string in other words.
Thank You for sharing this code.
Send the code. I am facing a similar kind of problem. In the comment section.
thank you it is very easy to understand and this is what i was looking for .
how easy is this tutorial to adapt to viewing database information when there is no authenticated user? so pretty much list all database contents (still quite new to this)
i got a null pointer error from show data method
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.testapp.ModelFarmer.getFarmerID()' on a null object reference
Sir! While retrieving data given child is not present in firebase means how should we diplay that database is empty??
where did the code determine what user information is Blake's, why didn't it return everything from the data base
with your previous videos. It only sign in the user if the user with same email and password doesn't exist. but existing user cant sign in with email and password .. what should i do ? plz help
where did you take from the "mListView "and then .setAdapter - first of all i didn't see that you add variable called "mListView" and also ".setAdapter" method not shown in this tutorial video.
please help!
This method is not working when the data is being saved like Root name --> UserID -- > unique ID -- > name.
Could you please help with this?
What if I have 3 objects Users, Contacts, Vehicles what is the right reference? and how to check if the data is empty. Just like for example I have an application that could add contacts with contact information(firstname, lastname, contact number, email) how to check disable the method showData if there is no registered UID ?
Dear,
this application is unfortunately stop after successfully login to firebase auth. (In my case)
have u any soltution for this?
bro i need a lil help
in valueEventListener is it possible to get the key string of the snapshot using snapshot.getkey() ???
actually i used it but it gives me null value
for example: like in this video you showed ur database
for example you want to get all of the users data including the user id without inserting the UID along with name, email, phone in the database Bcause its already available at parent
so by referencing from 'users' reference if i crawl over all users and get the values then it gives all the name, email, and phone but i can't find a way to get the key string that i crawl using the "users" snapshot
please help me out bro i've looked all over the internet but can't find the solution😣😣...
my listview is oin the main activity i think my app is crashes if i put this code inside my mainAct.
and where is the simple_list_item_1?
Mitch Please Help , This does not work when there are 2 or more nodes in the database.
My setEmail, setName and setPhone are showing in red with 'cannot solved method'. where did I go wrong?
How to use users' datas from Excel file to confirm login success or failed? Please.
How do you use Kotlin Coroutines to retrieve data from Firebase Database?
Hello, thankyou for this wonderful and straightforward tutorial, but I'm having a bit of a problem as 'getUid' produces java.lang.NullPointerException.
I'm using userKey for my firebase. But in the Authentication there is clearly a UID for every signup made. So it was supposed to get that right? Instead of a null. I tried experimenting and refred to the database via userKey and used 'ds.child(StringValueOf (userKey)) in the 'ds.child(userID)' but the problem here is that it crashes as a running time error. I'm quite confused here can you help me a bit Mitch? I really want to implement your way of doing this. Thanks!
have you found the solution?
I want to play CZcams video in my app i want to get data from firebase but youtube api need a video id what to do
how can i retrieve data by using its id from database
im not talking about eventlisteners
there must be a way that we can do any run time
is it same to retrive data in a fragment
and how use fetched data out of scope of on datachenged ?
Hi Mitch. I'm sorry but the tutorial kind of doesn't demonstrate the key use of the ValueEventListener object. I was hoping you'd show the changes on your screen as the data changes in the db, or could I be wrong? I'm fairly new to both Android and Firebase.
Yeah you're right. A ValueEventListener is for getting realtime updates. If you don't want constant updates you shoudl use a "addListenerForSingleValueEvent". firebase.google.com/docs/database/android/read-and-write#read_data_once
How to put other info such as first name, middle name and last name in the database after signup with email and password? Help please.
thanx for this video .... I am stuck at getting data entered chronologically after user authentification.. plz help me with this
I have a error helpppppppppppp
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.smarpitsingh.firebaseapp.UserInformation.getName()' on a null object reference
I'm having the same error did you ahve a solution to this?
FIRIYUU.Espina make changes in firebase database .
What changes did you make? Exactly?
FIRIYUU.Espina look at database at 0:37, there is parent directory named as users . In my case I did not create this parent directory .So match the database exactly with mitch database . look at 0:37
the data in firebase should be in string type
Hi Mitch,
First of all thank you so much for putting these tutorials together. Out of all of the tutorials I have found yours are so much easier to follow.
I have code working for this particular tutorial, however when I add another top level child, the app crashes. It's like Firebase doesn't know where to look anymore, and I know it has to do with where I am looking in myRef (I think).
For example I have Users Child tree and Companies child tree. If I remove Companies, everything works well. As soon as I add a company the crash occurs with a null pointer exception.
if you have the time, can you shed some light on this please?
Thanks in advance!
Michael
Thanks mate.
I will keep digging.
Classes seem to be setup correctly and created using Getter/Setter generator.
I will let you know how I go.
Thanks again!
Hey Mitch,
Ive banged my head against a brick wall all day with no joy.
If I have one top level child (in my case Consultants), i get the current logged in users info no probs.
As soon as I add other top level children (eg Companies, Customers) i get a null pointer exception crash on Consultants.getName().
Would the code iterate through the class specified in showData(dataSnapshot) and return the info from the specific child branch, in this case user.getUid() located in Consultants?
myJSON data...
{
"Companies" : {
"-Km0TuR-w1iGHTF35rDG" : {
"address" : "",
"companyname" : “Harvey Norman“,
"email" : "",
"phone" : "",
"state" : "",
"suburb" : "",
"zip" : ""
},
"-Km0U0V0XvlFtD0_DJ4_" : {
"address" : "",
"companyname" : “Redhot Internet Solutions”,
"email" : "",
"phone" : "",
"state" : "",
"suburb" : "",
"zip" : ""
}
},
"Consultants" : {
"hL3dEFTsr1Umhqkl9Q2PZ3vJwVg1" : {
"address" : "",
"email" : "",
"name" : “Joe Bloggs“,
"phone" : "",
"state" : "",
"suburb" : "",
"zip" : ""
}
},
"Customers" : {
"hL3dEFTsr1Umhqkl9Q2PZ3vJwVg1" : {
"address" : "",
"email" : "",
"name" : "Rosie Banks”,
"phone" : "",
"post_code" : "",
"state" : "WA",
"suburb" : ""
}
}
}
Sorry to be a pain. Thanks again for your help.
Michael
Hi Mitch,
After implementing your code I found that when I have only the one child node, Consultants, the code and app run nicely. As soon as I add a second or subsequent node, for example Companies or Customers, dataSnapshot trys looking for the getName() in the last node created.
In the case of my Companies class there isn't one (a userID) and that is where the app crashes. There is a getName() property on the Customer class but after a while the app crashes as the logged in userID doesn't match the one dataSnapshot retrieved from the incorrect class.
Am I creating the data incorrectly? Should I only have one top level child node, say Companies, then build Consultants and Customers under that first node?
For example:
Companies
Companies/Consultants
Companies/Consultants/Customers
Where I am going with this is Customers in a normal one to many type database may have many Consultant and Companies but a Consultant may have only one Company and a Company would have many Consultants and Customers.
Is Firebase the right database tool to use or should I revert to an SQL type database?
Thanks heaps in advance too . I know this is taking up your valuable time. I really have found your videos easy to follow and understand.
Michael
Thanks Mitch. with your help ive got this far. i will soldier on and get it together.
i think too, i will go through your other tutorials. They are pretty spot on.
I Agree MR Michael Cockinos
I have an error ,please help ,java.lang.null reference ,getEmail(),how to solve it?
have you fixed it? im still getting this error
Hello sir, why when i add new child other than "users" i got this error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.user.firebasesample.UserInformation.getName()' on a null object reference"
have you fixed it yet? same problem here
How to perform select all users operation in single network call base on child attribute.
like as : select * from users where name='mitch'
Hey there I'm creating a chat app and I send msg to a child in firebase and I retrieve the msg of others through onDataChange in value event listener but the problem is when I retrieve msg I their particular activity page it works well but when I leave that page and moves to another person chat and comes back to his chat page Im receiving his last chat against due to the value event listener so I have done another way. It is I have deleted the msg from firebase once I have read it from firebase and put an if condition at onDataChange stating if the firebase value is not empty then perform the task inside onDataChange else not . now it works well but when I go back for twice or thrice and comes back the new msg from him is displaying twice or thrice accordingly to me pls help me.
Hi Mitch , How can I check if there is data for this user?? I cannot use myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
because they are not methods I can call on, can I ??
And where can I call checking database value? onCreate only run when the app starts... Which code does it repeat whenever an activity(Main Page) is loaded? Thanks
Hi! I'm new here and I have the same question. If a user doesn't have data, how can I ignore it so I don't get an error while running the app? Thanks
Hello good man, i really enjoyed with your tutorial,you really know how
to explain,so i have one issue that i would like you help me. The issue
is this,is there any other way of displaying the multiple data (eg. Id,
name, age and so on ) retreived from the firebase realtime database in
listview? To be clear,i mean to get all the data id ,name,age for one
record in a sigle row of the listview?
You should use firestore instead. It's better. Watch my firestore playlist
Hi, Mitch thanks for sharing this valuable content to understand very easily... please make one more tutorial for phone authentication with OTP to connect with firebase database... If anyone knows about this means please let me know or suggest any documentation...
Thank u.
Yo Everything Even Twitter Sign-in is Also Available On the Github Firebase Quick start Database repository. Fork it as much as you want !
Hi bro, Why it say null point error when my database have more than 1 child?
I need code to get data from attributes with comparing various values in firebase database
How to retrieve only a single information in textview?
error here uInfo.setName(ds.child(userID).getValue(UserInformation.class).getName()); it give me null
I have same problem.
Check if your UserInformation attributes match exactely what is in firebase
thank you soo much
Hi Mitch,
Your videos are helpful.
I just want to know whether I can read data on a button click.
Thanks in Advance....
Yes of course. Just attach an OnClickListener to a button and then do the query.
But a better way would probably be to just do the query when the activity or fragment is inflated, then ONLY display the data when the button is clicked. That would be more efficient.
How do I put data in a text views
How to retrieve data only if a value matches to the entered value
I want to substract the value of database from the value obtained from edittext how to do it??
Have you resolved this? I'm trying to do the same thing.
@@elizajaropojop1743 yeah I have solved this
Dear sir, Greetings of the day! I want to create an app which can extract data from excel, csv, xlsx formats and save into android sqlite database and then plot it in Mpandroid chart. If you could help me , please prepare series on it, in kotlin. Searched on youtube but couldn't find good tutorial Thanks in advance
thanks bro
Ok so onDataChange() gets called whenever the activity starts.... That's good to know, thank you so much xD
When i start ViewDatabase activity it signs out
How do I retrieve and show a value from a specific node?
dbinstande.child(tablename).child("specific node").addListenerfor....
I have a problem loading the data from the database when the activity is created, it seems like onChange only works when data in database changes
thanks alot man
Can i get a link to the instagram clone course
One last thing, do you know of any sites where i can find a mentor as I am only 16 and have a lot that i want to learn and i would appreciate help from anyone willing to mentor me, thanks
will do, thanks again for answering my questions, really appreciate it
When i start ViewDatabase activity it signs out. What am i missing ?!
same here
tks man!
how i get all userIds of user not the userIDs data...i want to read all the user id's of Users
hey mitch, can you please also make a video for ChildEventListener?
if you get NullPointerException, make sure one child is not called
for example,
you want street from city from countries.
you should not write "city" in the child.
like this
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("country");
then you call the for loop and inside the for loop
ds.child("street").getValue()...
the parent of the children must not be called at all
could you possibly make a tutorial to show how to read data (.ie name, number, email) from logged in users with firestore please?
did you saw any other tutorial?
Hello Sir! Thanks for Great Tutorials
i have an issue please Help i retrieve data from firebase real-time database into my blog app, but when the live user increase above 800 - 1k, then nothing loading from firebase
how to solve this issue , please Help
It's a limitation bruh ! The Firebase databases doesn't scale up to large number of users ! Consider upgrading to Firestore !
then how to view images....?? picasso...? can you make a video for that .....?
hello please help when i'm login into system how retrieve userID from authentication and use it as unique id for user when login make a connection between authentication and database to retrieve name and phone number for a unique user logged in into system and have a one ID unique in auth and database, I need signup with createUserWithEmailAndPassword() method and adding some data for user such as Name and Phone Number when adding this data i need using all this data in profile Activity where Auth and database
PLEASE HELP ME!!
ThankYou.
I need signup with createUserWithEmailAndPassword() method and adding some data for user such as Name and Phone Number in database, i need list all this data in profile Activity for the same user!!
Firebase 11.0.1 not work
what if i want to give unique phone number to each user. i mean if one phone no. is alrdy used so other users cant use that number again. please make video about this.
You can do that via phone authentication
clicking view database contents doesnt show me anything..but the login and password part is fine...something is always not working with my display contents from database please helpppppppppp!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!...its important
Dont know why but when i tried different videos it is not getting data into list view thats the major problem im facing ...plz help i have to work on big project
how can we retrieve data from the nested child from firebase in android ... which have more than 10 value of the nested child
Hey.. did you find how to do that?
nope ...I am using the array to get the data but nothing is coming useful and while using datacapture(), it shows the data but in a random manner. not in which I saved it.. :'(
make a video for login and registration using real time database
I write the exact same code just like you but i don't know whats going wrong it doesn't pulls any of the data from database.
Can someone please help me?
have you found the solution ? im getting the same error
I'm getting error like no setter/field found
Hello, thank you for this great tutorial. The only problem I had was getting null in show data method. I have fixed it like this ->
for(DataSnapshot ds: dataSnapshot.getChildren()){
if(ds.getValue(User.class).getId()==id) { //optional
user = ds.getValue(User.class);
im getting the null ref error, could you what exactly am i suppose to do to fix it?
if(ds.getValue(UserInformation.class)getId()==id{
uInfo = ds.getValue(UserInformation.class);?
it says cannot resolve the symbol id and getid
Hi Mitch, the app would crash if the user has no data in the database... Maybe I can catch it at dataSnapshot.getChildren() ? How to do it? Please help. Thank you.
Hi Mitch, could you tell me how to check it? The app crashed even when I check for empty database with "for (DataSnapshot ds : dataSnapshot.getChildren()) " ... I guess that's not the way to check it... Please help. Thank ou
Mitch, I found it. The error happens at ds.child(userID);
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child() ... so I use try and catch got it to avoid crashing. Is that good enough? Thanks
Hi, Mitch, this video is very helpful but I have a problem I seem to have this error uInfo.setName(ds.child(userID).getValue(UserInformation.class).getName()); in this part it always gives me NullPointerException how can i solve this thank you :)
I also have the same error , do you solve it ??
I think it is because you are trying to get userId but you have you used myRef.push().getKey() which is different than authentication's UID and when you register name and other user details in the database, just use userID from the authentication for unique key instead of push().getkey(); like below. Then when you try to viewDatabase then you will be using same UserId to access the current user's details.
FirebaseDatabase firebaseDatabase;
DatabaseReference myRef;
FirebaseAuth mAuth;
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
id = user.getUid();
// Write a users to the database
firebaseDatabase = FirebaseDatabase.getInstance();
myRef = firebaseDatabase.getReference().child("users");
/////////////////
UserInformation addUsersDetails = new UserInformation(firstName,lastName,dateOfBirth,email,password,street,suburb,townCity,postalCode,phoneNumber);
myRef.child(id).setValue(addUsersDetails);
startActivity(new Intent(RegisterDetails.this,HomeActivity.class));
toastMessage("Registered succefully..");
what is TAG ?
hey dude i am getting Null time exception error. I have copies copies and pasted your code line bu line to suit my project. Please help
stackoverflow.com/questions/48813524/why-am-i-getting-a-null-pointer-exception-when-reading-user-data-from-firebase
This maybe of help. I did the same thing.
@@craigmartin1855 i tried the stack overflow link but still getting null ref, what changes did you make exactly in your code?
@@stonerrawhunter5968 so i've fixed, here's my solution
myRef.child("users").child(UserID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange( DataSnapshot dataSnapshot) {
UserInformation user=dataSnapshot.getValue(UserInformation.class);
txt_name.setText(user.getName()); }
No need showData
I just want to say how poorly named this function is given it is also their most basic simple read. I spent too long searching for a basic read method when this is it. Bad design. Thank you for posting you saved me time
how to show only name in Textview rather than list view?
I did it but really confuse me, I try all ways i know and didn't work with me, can you help me plz?
Love u
Can i request that you do a tutorial on displaying all data on firebase without auth.
EN EN just set the database rules to true. Then anyone can read without being authenticated
M getting null point exception in the " for " loop
have you found the solution?
How can i display name in a TextView?
Yo. Were you able to solve it?
Hi there my app was crash forced stop
Hi Mitch, so finally the best way to do this is to put all ds.child() in a try-catch!
private void showData(DataSnapshot dataSnapshot) { for (DataSnapshot ds : dataSnapshot.getChildren()){
UserInformation uInfo= new UserInformation();
try{ } catch (){}
i did the same but app still crashes when user do not have entry in database. pls share your code ...
how did you exactly implement this in your code? im stil getting the null ref error