I need a help in firebase database,
I am willing to create an app for a city like Kolkata, to find buses between different local stations, I want to save the data in database and user will input where to where they want to go, after clicking on search, list of available data will be shown,
But I need help in how should I save the data to fetch it easily with less complicated code.
You can save data easily with firebase
private void writeNewUser(String userId, String name, String email) {
User user = new User(name, email);
mDatabase.child("users").child(userId).setValue(user);
}
You can search from firebase like below
DatabaseReference mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
Query query = mFirebaseDatabaseReference.child("users").orderByChild("name").equalTo("Fazal");
query.addValueEventListener(valueEventListener);
ValueEventListener valueEventListener = new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
//TODO get the data here
User user = dataSnapshot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
};
EDIT:
Firebase dont have a great SQL like searches built in. You can either sort by values/key or you can equalto
https://firebase.google.com/docs/database/android/retrieve-data
for further details check fire-base documentation
https://firebase.google.com/docs/database/android/read-and-write
when you write data into firebase database used below code ..
make pojo class for insert data..
public class City {
public String name, code;
public City(String name, String code) {
this.name = name;
this.code = code;
}
}
then after when you insert data into firebase used below code..
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
mFirebaseDatabase = mFirebaseInstance.getReference("usersDb/UserTable");//define your database name and table name
}
// below method used insert data..
private void insertData(){
City city=new City("Ahmedabad","380016"); // you can add data also runtime.
mFirebaseDatabase.child(city.name).setValue(user);
}
// below method used to search data..
private void sqlQuery(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("usersDb").child("UserTable").orderByChild("name").equalTo("vikas#gmail.com");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot issue : dataSnapshot.getChildren()) {
Log.d("Value::",issue.getValue(User.class).email);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Related
I want to read data from my Firebase database for all questions. For e.g. for question1 I want to store ques,ans and answeredBy into three variables. What I am currently doing is here.
private FirebaseDatabase database=FirebaseDatabase.getInstance();
private DatabaseReference
quizRef=database.getReference("Quiz").child("Questions");
quizRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds:dataSnapshot.getChildren())
{
ModelClass modelClass=new ModelClass();
modelClass.setQues(ds.child("question1").getValue(ModelClass.class).getQues());
modelClass.setAns(ds.child("question1").getValue(ModelClass.class).getAns());
textViewQuestionText.setText(modelClass.getQues());
}
}
#Override
public void onCancelled(DatabaseError error) {
textViewQuestionText.setText("Error occurred");
}
});
Tried and Tested. You dont have to check for keys like question1,question2 etc
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference("Quiz/Questions");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
ModelClass modelClass = (ds.getValue(ModelClass.class));
modelClass.getAns();
modelClass.getQes();
// fetch any key value pair
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I recommend to use firebase generated hash keys instead of your own keys like question1,question2 etc
Check this
You can just use the data from your Firebase Database directly using the following code:
DatabaseReference q1Ref = quizRef.child("question1");
q1Ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String question = dataSnapshot.child("ques").getValue(String.class);
String answer = dataSnapshot.child("ans").getValue(String.class);
int ansBy = dataSnapshot.child("answeredBy").getValue(Integer.class);
// now you can do what you want with the values stored in the variables
}
#Override
public void onCancelled(DatabaseError error) {
textViewQuestionText.setText("Error occurred");
}
});
To read or write data from the database, you need an instance of DatabaseReference:
private DatabaseReference mDatabase;
// ...
mDatabase = FirebaseDatabase.getInstance().getReference();
To read data at a path and listen for changes, use the addValueEventListener() or addListenerForSingleValueEvent() method to add a ValueEventListener to a DatabaseReference.
You can use the onDataChange() method to read a static snapshot of the contents at a given path, as they existed at the time of the event.
For more information you can refer to firebase docs
I have a Firebase database of the following:
Root Node
User node
an automatically generated key generated by ref.push()
attributes
I am trying to retrieve only one of the attributes of a single child under the user. Here is a screenshot of my database:
Screenshot of my database
If you check the screenshot, i only want to retrieve email (assume i have no other way of getting it). However, in the code, I wouldn't know the child of User that contains the email I want. This is what i am currently doing but it is very inefficient (this code checks if my current user exists, if not, it adds his/her data to the database):
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("User");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for (DataSnapshot child:children) {
User user1 = child.getValue(User.class);
Log.d("kharas email",user1.getEmail()+"");
if(!user1.getEmail().equals(firebaseAuth.getCurrentUser().getEmail())){
GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
String birthday = "Not Available";
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
User userInfo = new User();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("User");
birthday = object.has("email")+"";
userInfo.setBirthday(birthday);
userInfo.setEmail(firebaseAuth.getCurrentUser().getEmail());
ref.push().setValue(userInfo);
}
}).executeAsync();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I tried to set the child under User to the email but firebase wouldnt let me use some special characters in the key. Any suggestions to make the code more efficient would be appreciated. Or any key suggestions that would make querying easier would be great.
Thanks in advance
Instead of putting random value or auto generated key you can add user's id which is received from fire base
firebaseAuth.getCurrentUser().getUid()
This will be more easy to access and will be more efficient because whenever you get will logged in, you will have this user_id and corresponding to user_id you can get email instead of checking all values in database
The only way to retrieve email if you dont know the random key is this:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("User");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){ for (DataSnapshot child:children) {
String email=datas.child("email").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Or you can use firebase authentication and add the userid under Users instead of push() then retrieve the userid :
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("User");
ref.child(userid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email=dataSnapshot.child("email").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
That way you do not have to loop.
I want to use the spinner to display the key which under specific username but unfortunately it returns nothing to the spinner. I used an array to store the key value which under the username.
Here's my database structure
Let's said I am rexyou0831 and I just want to retrieve the 2 usernames which under my username but my code return me nothing to the list. un is my current username variables. Please if you got any idea please share it with me thank you.
Hers' my code
db = FirebaseDatabase.getInstance();
cref = db.getReference("chat");
public ArrayList<String> retrieve()
{
final ArrayList<String> Student=new ArrayList<>();
cref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot c:dataSnapshot.getChildren())
{
if(c.getKey().equals(un)){
for(DataSnapshot d: dataSnapshot.getChildren()){
Student.add(d.getKey());
}
}else{
Student.clear();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return Student;
}
To get those usernames under your username, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("chat").child("rexyou0831");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userName = ds.getKey();
list.add(userName);
}
Log.d("TAG", list);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
Your out put will be: [gigi1212, mario123]
Note, that onDataChenge() is called asynchronous which means that is called even before you are adding those keys to the list. As a conslusion, you need to declare and use that list, inside onDataChenge(), otherwise is null.
I want to search a condition ,if student studied at 'swe' department then i will show name and id for every student who are studied at swe department.
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("user");
databaseReference.orderByChild("department").equalTo("swe").addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String str = dataSnapshot.child("department").getValue(String.class);
Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your current code fails to handle the fact that the result is a list. To solve this, loop over dataSnapshot.getChildren():
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("user");
databaseReference.orderByChild("department").equalTo("swe").addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String str = dataSnapshot.child("department").getValue(String.class);
Toast.makeText(MainActivity.this,str,Toast.LENGTH_LONG).show();
}
}
I have integrated Google sign-in in my app and i am pushing some data in to fire base including user U-id.I had researched a lot and didn't get anything the problem i am facing that i want to fetch Particular data for eg If User A sign-in and push 5 data and Then User B sign-in and push 3 data.I want a query like if User A sing-in Again it will get his 5 data only and not the data which is pushed by User B.Thanks in Advance :)
By using this it fetch all the data from firebase:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
FirebaseModel firebasemodel =
data.getValue(FirebaseModel.class);
firebasemodels.add(firebasemodel);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have tried all that .child .orderby and .equalTo but did'nt work
My Structure is Like:
My FireBase Structure
You also need a reference to the data, which isn't included in your code block. So something along the lines of (this should be before this):
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("notepad-secure/notepad");
Firstly add a user_id key in your child data, it will look like below :
id:"",
note:"",
title:"",
user:""
user_id:"{id from which user have you uploaded data}"
And than you can call below function with specific user data like
below Note : "user_id" = id from which user have you uploaded data
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("notepad").orderByChild("id").equalTo("user_id");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// dataSnapshot is the "notepad" node with all children with id
for (DataSnapshot notepad: dataSnapshot.getChildren()) {
// do something with the individual "notepad_data"
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To Fetch Particular values from the firebase,try this code
FirebaseDatabase database;
database.getReference().child("notepad-secure").orderByChild("id").equalTo(user).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
User userdet =childSnapshot.getValue(yourclass.class);
String note=userdet.note;
//Here you will get the string values what you want to fetch
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
First U have to differentiate.U have to implement Firebase Authentication the u can get Firebase UID of every USER.
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
Then store seperatly in new node.
i.e Take Firebase Database Instance and
databaserefernace.child("Data").Child("userID);
When your add a user data to Firebase database, you can add it using the specific uid provided by the FirebaseAuth object like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
Assuming you that your database strucure look like this: Firebase root -> notepad-secure -> notepad, to retrieve data, you can use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference notepadRef = rootRef.child("notepad-secure").child("notepad").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String id = dataSnapshot.child("id").getValue(String.class);
String note = dataSnapshot.child("note").getValue(String.class);
String title = dataSnapshot.child("title").getValue(String.class);
String user = dataSnapshot.child("user").getValue(String.class);
Log.d("TAG", id + " / " + note + " / " + title + " / " + user);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
notepadRef.addListenerForSingleValueEvent(eventListener);