How to insert data in the firebase - java

So i have problem regarding adding the appointment details in my firebase android studio. I want the user to store their appointment details in appointment database and I also want to check if the user has booked the date and day. However , after the user has pressed the confirm button, it doesnt store the appointment details in the firebase and it also doesnt prompt the dialog message to the user indicating that their appointment has been registered successfully? Is there any way to solve this problem ? The code is shown as below :
private void addAppointment() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("idPatient", FirebaseAuth.getInstance().getCurrentUser().getUid());
hashMap.put("idDoctor", idDoctor);
hashMap.put("time", time.getText().toString());
hashMap.put("date", day.getText().toString());
hashMap.put("status", "On hold");
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference("Appointment");
reference1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot data : snapshot.getChildren()) {
Appointment relationship = data.getValue(Appointment.class);
if (relationship.getTime().equals(time.getText().toString()) && relationship.getDate().equals(day.getText().toString()) && relationship.getIdDoctor().equals(idDoctor)) {
new SweetAlertDialog(BookAppointmentActivity.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("The date and time has been booked")
.show();
}else if(snapshot.exists()){
reference.child("Appointment").push().setValue(hashMap);
new SweetAlertDialog(BookAppointmentActivity.this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Congratulations")
.setContentText("Your appointment is registered successfully")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
Intent intent = new Intent(BookAppointmentActivity.this, MainActivity.class);
startActivity(intent);
}
})
.show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});

Also check the firebase rules, read and write are set to true as per your requirements

so first of all you can create a modal class for all the children (example - doctor, time, status )
package com.example.chatapp;
public class UserModel {
String name;
String phone;
String about;
String url;
String uid;
public UserModel(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
then declare this modal class
Usermodal modal = new Modal class
then insert data like
modal.setname(yourdata);
then write
databaseref.child(key).setvalue(modal);
you can refer to this link for more.

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 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.

How to add Name along with email and password to firebase database android

How can I add Name along with email and password to firebase database android?
I added an email and password with function createUserWithEmailAndPassword and call a function:
createNewUser(task.getResult().getUser());
when successfull and in createnewUser im doing this
private void createNewUser(FirebaseUser userFromRegistration) {
String username = nameEditText.getText().toString();
String email = userFromRegistration.getEmail();
String userId = userFromRegistration.getUid();
User user = new User();
user.setName(username);
user.setUid(userId);
user.setEmail(email);
Log.d("Raza",mDatabase.child("users").push().setValue(user).isSuccessful()+"");
}
But I'm getting False at Log.d and the username is not added to my database.
My User Class is this:
public class User {
String name;
String uid;
String email;
public User(){
// Default constructor required
}
public void setName(String name){this.name = name;}
public void setUid(String uid){this.uid = uid;}
public void setEmail(String email){this.email = email;}
public String getName(){return this.name;}
}
Please help me on this.
Model Class
public class User {
public String uid;
public String email;
public String user_name;
public User(){
}
public User(String uid, String email String user_name)
{
this.uid = uid;
this.email = email;
this.user_name=user_name;
}
}
and Push data into firebase data like that
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
User user = new User(firebaseUser.getUid(),
firebaseUser.getEmail(),
MySharedPreferences.getString(Constants.KEY_USER_NAME));
database.child(Constants.ARG_USERS)
.child(firebaseUser.getUid())
.setValue(user)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// mOnUserDatabaseListener.onSuccess(context.getString(R.string.user_successfully_added));
} else {
// mOnUserDatabaseListener.onFailure(context.getString(R.string.user_unable_to_add));
}
}
});

How to iterate through a Firebase structure in Android?

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.

Failed to bounce to type with push Id Firebase

Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "-Jzp5XCUx78BX5D7BvkU"
My POJO class
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
public class ChatData {
String messageId;
String userName;
String currentDate;
String chatType;
String messageType;
String currentLocation;
public ChatData() {
}
public ChatData(String messageId, String userName, String currentDate, String chatType, String messageType, String currentLocation) {
this.messageId = messageId;
this.userName = userName;
this.currentDate = currentDate;
this.chatType = chatType;
this.messageType = messageType;
this.currentLocation = currentLocation;
}
public String getMessageId() {
return messageId;
}
public String getUserName() {
return userName;
}
public String getCurrentDate() {
return currentDate;
}
public String getChatType() {
return chatType;
}
public String getMessageType() {
return messageType;
}
public String getCurrentLocation() {
return currentLocation;
}
}
Message Receiving side
public static final String CHAT_TYPE_FRIEND = "friend";
and currentChannel=6ca5c08c-9dd2-4f8f-8475-34a427c2354f
// User node listener were all the user private messages arriving
private void listenToUserNode() {
try {
Firebase mFirebaseRef = new Firebase(Constants.FIRE_BASE_URL).child(Constants.CHAT_TYPE_FRIEND + File.separator + currentChannel);
mFirebaseRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String key = dataSnapshot.getKey();
ChatData newMessage = dataSnapshot.getValue(ChatData.class);
handleReceivedMessage(currentChannel,newMessage);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Am facing an error while receiving a data from firebase onChild changed as my pojo is matching with the data but it throws error because there is no field for push id
Note that this answer is based based on the incomplete code you posted. It would be really helpful if you add the code that sets up the Firebase reference and calls getValue() to your question.
It looks like you're trying to read a list of chat messages into aChatData object:
Firebase messagesRef = new Firebase("https://yours.firebaseio.com/messages");
messagesRef.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
ChatData data = snapshot.getValue(ChatData.class);
}
public void onCancelled(FirebaseError firebaseError) {
}
}
That won't work.
You have two options:
Read each message in a loop
In this snippet we'll use snapshot.getChildren() to iterate over the individual messages.
messagesRef.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot child: snapshot.getChildren()) {
ChatData data = child.getValue(ChatData.class);
}
}
public void onCancelled(FirebaseError firebaseError) {
}
}
Read all messages into a map
Alternatively we can read all messages into a map:
messagesRef.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
GenericTypeIndicator<Map<String,ChatData>> chatsType = new GenericTypeIndicator<Map<String,ChatData>>() {};
Map<String,ChatData> chats = child.getValue(Map<String,ChatData>);
}
public void onCancelled(FirebaseError firebaseError) {
}
}
If you don't care about the push IDs for the messages, you can chats.values(). But in that case you might want to consider why you're storing the messages with push IDs in the first place, instead of using your own messageId value.

Categories

Resources