How to iterate through a Firebase structure in Android? - java

I want to create a function that iterates through a firebase structure looking like this:
{
"users":{
"7e122736-2dd4-4770-a360-a0e7cbe41a43":{
"currentLatitude":46.6598714,
"currentLongitude":23.5637339,
"displayName":"gjsj2",
"email":"2#vlad.com",
"password":"123"
},
"a09e7e1d-ad3a-4d21-b0ba-069e0999bb93":{
"currentLatitude":47.6599014,
"currentLongitude":23.5636797,
"displayName":"gjsj",
"email":"1#vlad.com",
"password":"123"
},
"abc29286-fd6d-4088-95da-759828b5835d":{
"currentLatitude":50.6599043,
"currentLongitude":23525.5637188,
"displayName":"gjsj3",
"email":"3#vlad.com",
"password":"123"
}
}
}
I want to create a function that takes every unique user id's child and uses his coordinates to create a marker on a google maps map. Here's what i got so far but it doesnt seem to be working :
public void onChildChanged(DataSnapshot snapshot, String s) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
for (DataSnapshot uniqueUserSnapshot : userSnapshot.getChildren()) {
Users currentUser = uniqueUserSnapshot.getValue(Users.class);
MarkerOptions options = new MarkerOptions()
.title(currentUser.getEmail())
.icon(BitmapDescriptorFactory.defaultMarker(getRandomNumberInRange(0, 360)))
.position(new LatLng(currentUser.getCurrentLatitude(), currentUser.getCurrentLongitude()));
mMap.addMarker(options);
Toast.makeText(MainActivity.this, "fsafasfasfas", Toast.LENGTH_SHORT).show();
}
}
}
And here's my Users POJO:
package com.licenta.vladut.mmap;
public class Users {
String email;
String displayName;
String password;
double currentLatitude;
double currentLongitude;
public Users() {
}
public Users(String email, String displayName, String password, double currentLongitude, double currentLatitude) {
this.email = email;
this.displayName = displayName;
this.password = password;
this.currentLongitude = currentLongitude;
this.currentLatitude = currentLatitude;
}
public Users(String email, String displayName, String password) {
this.email = email;
this.displayName = displayName;
this.password = password;
}
public String getDisplayName() {
return displayName;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public double getCurrentLongitude() {
return currentLongitude;
}
public double getCurrentLatitude() {
return currentLatitude;
}
}

If I understand the question correctly, you are actually close to what you want to do. Reference the database child user, and then add a ValueEventListener:
Firebase userRef = new Firebase(/*url*/);
userRef = userRef.child("users");
userRef.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot uniqueUserSnapshot : dataSnapshot.getChildren()) {
...
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
ValueEventListener returns the node called, not children one by one.

Related

Getting the current User information from Firebase Realtime Database

I developed a login app in Java where the user can login using their emailaddress and password. This works fine so far, but I have the problem that my UserModel.java is null when I get to my home activity. This also makes sense to me since Firebase Auth only checks the email and password and does not select the relevant information from the realtime database. I have therefore inserted a datasnapshot, this also works in the intended way since the system outputs the desired name.
My question is now how can I assign this datasnapshot to my UserModel so that my UserModel is no longer null (is it?!). In the last part of my HomeActivity you can see a String which should contain the Users Name, however even if I log in with an existing account this String is only showing the "Example Name". Due to the fact that the system is printing out the correct name I believe the DataSnapshot works as it should.
Thanks for your help!
part of my HomeActivity
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
final FirebaseDatabase database =FirebaseDatabase.getInstance();
DatabaseReference myref=database.getReference("Users").child(firebaseAuth.getUid());
myref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserModel userModel= dataSnapshot.getValue(UserModel.class);
System.out.println(userModel.getName());
currentUser=userModel;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(HomeActivity.this, ""+databaseError.getCode(), Toast.LENGTH_SHORT).show();
}
});
if(currentUser!=null) {
Common.setSpanString("Hey, ", currentUser.getName(), txt_user);
}
else{
UserModel userModel = new UserModel(uid,name,address,phone,email,password);
userModel.setName("Example Name");
Common.setSpanString("Hey, ", userModel.getName(), txt_user);
}
UserModel
private String uid, name, address, phone, email, password;
public UserModel() {
}
public UserModel(String uid, String name, String address, String phone,String email,String password) {
this.uid = uid;
this.name = name;
this.address = address;
this.phone = phone;
this.email = email;
this.password = password;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() { return password; }
public void setPassword(String password) {
this.password = password;
}
}
part of my Common class
public static UserModel currentUser;
I have now put both parts of the code together and was able to display the string with the correct name. However, the Common.CurrentUser is not initialized what is not a problem as long as the Attributes are alright.
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
if(firebaseAuth.getCurrentUser()!=null) {
final FirebaseDatabase database =FirebaseDatabase.getInstance();
DatabaseReference myref=database.getReference("Users").child(firebaseAuth.getUid());
myref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserModel userModel= dataSnapshot.getValue(UserModel.class);
System.out.println(userModel.getName());
Common.setSpanString("Hey, ", userModel.getName(), txt_user);
currentUser=userModel;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(HomeActivity.this, ""+databaseError.getCode(), Toast.LENGTH_SHORT).show();
}
});
}else{
UserModel userModel = new UserModel(uid,name,address,phone,email,password);
userModel.setName("Example Name");
Common.setSpanString("Hey, ", userModel.getName(), txt_user);
}

How to retrieve data from Firebase that have 2 layer structure?

I have 2 layer structure of table inside my Firebase. I have problem with retrieving this. How can I retrieve this data from my Firebase? I have provided my main code and my Order class.
here is my code
databaseReference = FirebaseDatabase.getInstance().getReference("Order");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
orderList = new ArrayList<>();
for (DataSnapshot orderSnapshot : dataSnapshot.getChildren()) {
orderList.add(orderSnapshot.getValue(Order.class));
}
psOrderAdapter PsOrderAdapter = new psOrderAdapter(orderList);
recyclerView.setAdapter(PsOrderAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ManageOrder.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
public class Order {
public String cust_id;
public String pro_id;
public String total;
public String name;
public String address;
public String phone;
public String status;
public String date;
public String dateTime;
public Order() {
}
public Order(String cust_id, String pro_id, String total, String name, String address, String phone, String status,String date, String dateTime) {
this.cust_id = cust_id;
this.total = total;
this.name = name;
this.address = address;
this.phone = phone;
this.pro_id = pro_id;
this.status = status;
this.date=date;
this.dateTime=dateTime;
}
//getter and setter
}
I'm expecting a result a result like this
Try the following:
for(DataSnapshot orderSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : orderSnapshot.getChildren()) {
orderList.add(ds.getValue(Order.class));
}
}
Add another for loop to be able to retrieve the data.

How to retrieve data using email from firebase realtime databse?

I have a database from firebase. I want to retrieve some data using a user's email. suppose user put his/her email if the email exists in the firebase database then it shows his/her username and password. I am not using firebase authentication, I am using firebase realtime database.
here is my database structure:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgate_password);
emailf = findViewById(R.id.emailf);
userf = findViewById(R.id.usernamef);
passwordf = findViewById(R.id.passwordf);
ok = findViewById(R.id.okbtn);
database = FirebaseDatabase.getInstance();
users = database.getReference("Users").child("emailAddress");
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signInMethod(emailf.getText().toString());
}
});
}
private void signInMethod(final String email) {
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
if (dataSnapshot.child("emailAddress").exists()){
if (dataSnapshot.child(user.getUserName()).exists()){
Toast.makeText(ForgatePassword.this,"User already exists",Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Tag", "Email not exists", error.toException());
}
});
}
here is my model class:
public class SignInUpModel {
private String fullName;
private String userName;
private String schoolName;
private String className;
private String division;
private String phnNumber;
private String emailAddress;
private String reference;
private String password;
public SignInUpModel() {
}
public SignInUpModel(String fullName, String userName, String schoolName, String className, String division, String phnNumber, String emailAddress, String reference, String password) {
this.fullName = fullName;
this.userName = userName;
this.schoolName = schoolName;
this.className = className;
this.division = division;
this.phnNumber = phnNumber;
this.emailAddress = emailAddress;
this.reference = reference;
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getPhnNumber() {
return phnNumber;
}
public void setPhnNumber(String phnNumber) {
this.phnNumber = phnNumber;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
How can I do this?
Using firebase database to create your own authentication system is not a good idea.
What you want to do will require you to allow read of every user's email password stored in database. This will be a huge security risk for your app as anyone can read all the email passwords in your database.
Firebase provides easy to use firebase authentication with many options to use. You can easily delegate the security to firebase auth and store your user's profile and data in db. This way you can also restrict data access for each user (which is why you want email password login for your app).
Please see the authentication documents of firebase: https://firebase.google.com/docs/auth
It will help you create your app without implementing your own auth and focus on actual features development.

Android Firebase: Hashmap can't be cast to a given Object type

I'm trying to query a firebase database to check if the user exists so, I can log them in. But, a strange issue has blocked me completely:
Query Code
String email = emailEditText.getText().toString();
String password = emailEditText.getText().toString();
fbUsers.orderByChild("email").equalTo(email).limitToFirst(1).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
HashMap<String, User> usersHashMap = (HashMap<String, User>) dataSnapshot.getValue();
Map.Entry<String, User> firstEntry = usersHashMap.entrySet().iterator().next();
User foundUser = firstEntry.getValue();
Log.d("Login: ", foundUser.getEmail());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
User Class
public class User {
private String email;
private String password;
User() {}
public User(String email, String password) {
this.email = email;
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
The strange issue is that the compiler says ALL OK but, in the runtime environment, this exception is thrown at Log.d()
java.lang.ClassCastException: java.util.HashMap cannot be cast to
com.example.project.User
This code uses getChildren().iterator().next() to get a snapshot for the single query result.
fbUsers.orderByChild("email")
.equalTo(email).limitToFirst(1)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
if (iter.hasNext()) {
User foundUser = iter.next().getValue(User.class);
Log.d("Login: ", foundUser.getEmail());
} else {
Log.w("Login: ", "No match: " + email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
if (databaseError != null) {
Log.e("Login: ", "onCancelled: " + databaseError.getMessage());
}
}
});
Have you tried calling getValue(User.class) ?

Android Firebase Database - not appropriate Object conversion from Database structure

My database structure is like this:
users
8aWcF6GQmpezfJkVnW5uYoJ2wtI3
email: "jack"#mail.com"
height: "180cm"
imgUrl: "https://www.goldennumber.net/wp-content/uploads..."
matches
WEZ36bsEFXQtrJWQJVT3KMtsgQC3: true
8oqmrMVZ57XXlunIAUEeBgKFZ0h2: true
uid: "8aWcF6GQmpezfJkVnW5uYoJ2wtI3"
username: "jack"
I am trying to convert this structure to this object:
public class UserMatchDTO {
private String uid;
private String username;
private String height;
private String imgUrl;
private String email;
private HashMap<String, Boolean> userMatches = new HashMap<>();
public UserMatchDTO() {
}
public UserMatchDTO(String uid, String username, String height, String imgUrl, String email, HashMap<String, Boolean> userMatches) {
this.uid = uid;
this.username = username;
this.height = height;
this.imgUrl = imgUrl;
this.email = email;
this.userMatches = userMatches;
}
public String getUid() {
return uid;
}
public String getUsername() {
return username;
}
public String getHeight() {
return height;
}
public String getImgUrl() {
return imgUrl;
}
public HashMap<String, Boolean> getUserMatches() {
return userMatches;
}
public void setUserMatches(HashMap<String, Boolean> userMatches) {
this.userMatches = userMatches;
}
public String getEmail() {
return email;
}
}
Here is the method where I convert this to my object:
final List<UserMatchDTO> userMatchDTOs = new ArrayList<>();
databaseReference.child("users").addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot matchSnapshot : dataSnapshot.getChildren()){
UserMatchDTO userMatchDTO = matchSnapshot.getValue(UserMatchDTO.class);
userMatchDTOs.add(userMatchDTO);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
However, when I debug this, the userMatches HashMap is always size 0. So why child "matches" from "user" is not converted to HashMap?
Here is what the snapshot looks like:
DataSnapshot { key = 8oqmrMVZ57XXlunIAUEeBgKFZ0h2, value = {email=jack#mail.com, height=180cm, uid=8aWcF6GQmpezfJkVnW5uYoJ2wtI3, imgUrl=https://www.goldennumber.net/wp-content/uploads/2013/08/florence-colgate-england-most-beautiful-face.jpg, username=jack, matches={WEZ36bsEFXQtrJWQJVT3KMtsgQC3=true, 8oqmrMVZ57XXlunIAUEeBgKFZ0h2=true}} }
Ok, so i manage to solve this, but I am not sure if this is good solution.
I just map the response to Object first and then cast this to the HashMap.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot matchSnapshot : dataSnapshot.getChildren()){
UserMatchDTO userMatchDTO = matchSnapshot.getValue(UserMatchDTO.class);
Object object = matchSnapshot.child("matches").getValue();
if(object != null){
userMatchDTO.setUserMatches((HashMap<String, Boolean>) object);
}
userMatchDTOs.add(userMatchDTO);
}
Is any better solution for this?

Categories

Resources