Adding data in Firebase realtime database using push() in Android Studio - java

I'm trying to make a feature in my hospital app which allows users to book appointment with doctor. So when they book appointments, the details such as date of appointment, patient email, doctor email, etc should get stored in both parent nodes named "Doctor Schedule" and "Patient Appointments". I'm trying to do this using push() in Firebase, but my app keeps crashing. Please help me fix it.
public class Book extends AppCompatActivity {
TextView selectedDate;
Button calenderButton,ok;
FirebaseAuth mAuth;
DatabaseReference docUser, patRef;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
Intent intent = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
String docEmail = intent.getStringExtra("message_key1");
String patEmail = intent.getStringExtra("message_key2");
String patname = intent.getStringExtra("message_key2.1");
String docname = intent.getStringExtra("message_key2.2");
String dphone = intent.getStringExtra("message_key2.3");
//Toast.makeText(Book.this, patname, Toast.LENGTH_SHORT).show();
selectedDate=findViewById(R.id.text);
calenderButton=findViewById(R.id.calender);
ok=findViewById(R.id.ok);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getInstance().getCurrentUser();
//docUser= database.getReference().child("Doctor Schedule");
MaterialDatePicker materialDatePicker=MaterialDatePicker.Builder.datePicker().
setTitleText("Select date").setSelection(MaterialDatePicker.todayInUtcMilliseconds()).build();
calenderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(),"Tag_Picker");
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
selectedDate.setText(materialDatePicker.getHeaderText());
Date=materialDatePicker.getHeaderText();
}
});
}
});
class Post {
public Post(String Date, String Patient,String Email,String Doctor,String Status) {
// ...
}
}
class Post1 {
public Post1(String Date, String Patient,String Doctor,String Email,String Phone,String Status) {
// ...
}
}
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Date != null) {
docUser = database.getReference().child("Doctor Schedule");
DatabaseReference newdocUser = docUser.push();
newdocUser.setValue(new Post(Date, patname,patEmail,docEmail,"Pending"));
patRef= database.getReference().child("Patient Appointments");
DatabaseReference newpatRef = patRef.push();
newpatRef.setValue(new Post1(Date,patEmail,docname,docEmail,dphone,"Pending"));
}
else {
Toast.makeText(Book.this, "Select date!", Toast.LENGTH_SHORT).show();
}
finish();
}
});
}
}

i think your app crashes when you call finish().
just remove that finish() and check if its getting updated in the database

Related

Why is my document reference returning a null string although there is no error

Here is my database structure:
Here is my full code
`
public class Homepage extends AppCompatActivity {
private View measure , history;
private Button signout;
private TextView txtwelcome;
FirebaseAuth fAuth;
FirebaseFirestore Fstore;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
measure = findViewById(R.id.measurecard);
history = findViewById(R.id.historycard);
signout = findViewById(R.id.btnsginout);
txtwelcome = findViewById(R.id.txtwelcome);
fAuth = FirebaseAuth.getInstance();
Fstore = FirebaseFirestore.getInstance();
userID = fAuth.getUid();
DocumentReference documentReference = Fstore.collection("users").document(userID);
documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
txtwelcome.setText("Welcome "+documentSnapshot.getString("Name"));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Homepage.this,e.toString(),Toast.LENGTH_LONG).show();
}
});
measure.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),measure.class));
}
});
history.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),history.class));
}
});
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
}
`
it just puts on the edit text welcome null it doesn't print any exception I've been trying for a while please help. Although when the user signs up it stores the data in the data base but I can't seem to fetch it.
I tried a snapshotlistner and successlistner on completelistner nothing worked , I excpected to see welcome hamza on my text view
You're getting null because the UID that is generated when the user is authenticated it's different than the document ID that exists in your database. Why do I say that? Because the length of the UID that comes from the authentication mechanism is 24 while the length of your document ID (RRUr...xhIB) is only 20. So most likely when you have added the users to Firestore, you have used the CollectionReference#add() method. That being said, your reference points to a document that doesn't exist, hence that null.
To set the UID as an ID of the document, you have to pass that UID to CollectionReference#document() method like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").document(uid).set(userObject);
// 👆
For reading the data, your code may remain unchanged.

How do I get data to show? My Firebase Realtime Database Still Says Null

I am trying to sync my Realtime Firebase database with my code.
I currently have Firebase Auth working, and I am able to get user ids, but my Realtime database stays on null. My Firebase Realtime database rules are currently set to true.
Is there something wrong with my code? I am trying to pull in the user id, first name, and last name into the Firebase Database.
public class Add_Info_After_Registration extends AppCompatActivity {
private EditText FirstName, LastName;
private ImageButton RegisterInfoButton;
private FirebaseAuth mAuth;
private DatabaseReference UsersReference;
//Firebase Things//
String currentUserID;
//Firebase Things//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__info__after__registration);
//this is referring to storing username information in firebase//
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UsersReference = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);
//this is referring to storing username information in firebase//
FirstName = (EditText) findViewById(R.id.add_info_first_name);
LastName = (EditText) findViewById(R.id.add_info_last_name);
RegisterInfoButton = (ImageButton) findViewById(R.id.register_submit_button);
mAuth = FirebaseAuth.getInstance();
RegisterInfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
SaveAccountSetUpInformation();
SendUserToMainActivity();
}
});
}
private void SaveAccountSetUpInformation()
{
String firstname = FirstName.getText().toString();
String lastname = LastName.getText().toString();
if(TextUtils.isEmpty(firstname))
{
Toast.makeText(this, "Please insert first name", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(lastname))
{
Toast.makeText(this, "Please insert last name", Toast.LENGTH_SHORT).show();
}
else
{
HashMap userMap = new HashMap();
userMap.put("firstname", firstname);
userMap.put("lastname", lastname);
//this is referring to storing username information in firebase//
UsersReference.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task)
{
if(task.isSuccessful())
{
SendUserToMainActivity();
Toast.makeText(Add_Info_After_Registration.this, "Your Account is Created Sucessfully", Toast.LENGTH_LONG).show();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(Add_Info_After_Registration.this, "Error Occured:"+ message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void SendUserToMainActivity()
{
Intent setupIntent = new Intent(Add_Info_After_Registration.this, MainActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
}

How to compare Firebase data with Login authentication screen input. Android

So I am making Login functionality and I need to compare the data I stored in Firebase with the input I am giving in the Login screen, so the user could login if he is registered in the system, right now it's working just for the first particular child from "Customer" but I need it to work with all so when I will add other users it could recognize them too. It should be compared with these 3 fields from database (email, password, active).
[The database] https://imgur.com/a/kL8AS3P
public class LoginScreen extends AppCompatActivity {
private FirebaseAuth mAuth;
private DatabaseReference mDatabase;
EditText email;
EditText password;
String username, pass, isActivate;
#Override
protected void onCreate(Bundle savedInstanceState) {
mAuth = FirebaseAuth.getInstance();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
email = findViewById(R.id.email_signin);
password = findViewById(R.id.passwordSignin);
mDatabase= FirebaseDatabase.getInstance().getReference().child("Customer").child("1");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
username = dataSnapshot.child("email").getValue().toString();
pass = dataSnapshot.child("password").getValue().toString();
isActivate = dataSnapshot.child("active").getValue().toString();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void backClick(View view) {
super.onBackPressed();
}
public void signIn(View view) {
if(allowedToSignin()){
Intent intent = new Intent(this, CustomerScreen.class);
startActivity(intent);
}
else {
Toast.makeText(LoginScreen.this,"Login failed!", Toast.LENGTH_LONG).show();
}
}
public boolean allowedToSignin(){
boolean signinAllowed = true;
if(email.getText().toString().equals(username) && isActivate.equals("true")){
email.setError(null);
}else {
email.setError("enter a valid email");
signinAllowed = false;
}
if (password.getText().toString().equals(pass)){
password.setError(null);
}else {
password.setError("enter a valid password");
signinAllowed = false;
}
return signinAllowed;
}
}```
[1]: https://i.stack.imgur.com/QvOla.png
I would do it the other way around.
1. Let the user sign in with Firebase Auth signin method.
2. Get their userid with `userId = mAuth.getCurrentUserId()`
3. Use this userId in your database to check if user is "active" if not signout the user automatically and throw an error on UI.
This means in your database userdata will be at mDatabase= FirebaseDatabase.getInstance().getReference().child("Customer").child(userId);

How to log in two different types of users to different activities automatically without having to log in again?

There's this android application I'm building with Firebase as the backend. It requires two different sets of users, a set of lecturers and a set of students. There's an issue however. I would want a student that has already logged in and closed the app to automatically log in to a different home activity when the student opens the app again. Same should apply to the lecturers. How do I achieve that? Can someone help with a sample code? I know about the functionality that firebase uses to automatically log in users to the homepage of an app but how do I specify the page that should automatically open if one is a student or a lecturer?
My Login Activity
public class LoginActivity extends AppCompatActivity {
private TextInputLayout mLoginEmail;
private TextInputLayout mLoginPassword;
private ProgressDialog mLoginProgress;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference jLoginDatabase, student_token_reference, lecturer_token_reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mLoginProgress = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
Intent main_intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(main_intent);
}
mLoginEmail = findViewById(R.id.login_email);
mLoginPassword = findViewById(R.id.login_password);
Button mLogin_btn = findViewById(R.id.login_btn);
TextView msignup = findViewById(R.id.sign_up_text);
msignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotosignup = new Intent(LoginActivity.this, ChoiceActivity.class);
startActivity(gotosignup);
}
});
mLogin_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = mLoginEmail.getEditText().getText().toString();
String password = mLoginPassword.getEditText().getText().toString();
if (!TextUtils.isEmpty(email) || !TextUtils.isEmpty(password)) {
mLoginProgress.setTitle("Logging in user");
mLoginProgress.setMessage("Please wait while we log you in...");
mLoginProgress.setCanceledOnTouchOutside(false);
mLoginProgress.show();
loginUser(email, password);
} else {
Toast.makeText(LoginActivity.this, "Please fill in credentials first", Toast.LENGTH_LONG).show();
}
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
} else {
// User is signed out
}
// ...
}
};
}
private void loginUser(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (task.isSuccessful()) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
String RegisteredUserID = currentUser.getUid();
jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(RegisteredUserID);
jLoginDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userType = dataSnapshot.child("userType").getValue().toString();
if (userType.equals("Lecturers")) {
mLoginProgress.dismiss();
Intent intentResident = new Intent(LoginActivity.this, LecturerMainActivity.class);
intentResident.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intentResident);
finish();
} else if (userType.equals("Students")) {
mLoginProgress.dismiss();
Intent intentMain = new Intent(LoginActivity.this, MainActivity.class);
intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intentMain);
finish();
} else {
mLoginProgress.hide();
Toast.makeText(LoginActivity.this, "Failed to authenticate user", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
super.onBackPressed();
}
}
This is a hack I used to solve the same issue. (Please note that this method may have security issues and I prefer using Firebase Custom Claims using Firebase Admin).
Create a LoginActivity using which you log in the user and after logging in, access the user type(admin, student, staff, paid whatever) in an UserTypeSelectorActivity and form this activity you can pass the user type to other activities using Intent data or shared preferences (which you feel better according to your app)
public class UserTypeSelectorActivity extends AppCompatActivity {
// Firebase Variables
FirebaseUser firebaseUser;
FirebaseDatabase firebaseDatabase;
DatabaseReference firebaseDatabaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Activity Name", getLocalClassName());
// Initializing Firebase Variables
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
firebaseDatabaseReference = firebaseDatabase.getReference();
if (firebaseUser != null) {
firebaseDatabaseReference.child("my_app_user").child(firebaseUser.getUid())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Check user type and redirect accordingly
if (dataSnapshot.child("admin").exists()) {
Boolean admin = dataSnapshot.child("admin")
.getValue().toString().equals("true");
if (admin) {
startActivity(new Intent(UserTypeSelectorActivity.this,
AdminActivity.class));
finish();
} else {
startActivity(new Intent(UserTypeSelectorActivity.this,
ClientActivity.class));
finish();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
Note: A precautionary warning that this is not a proper solution. It is how I have implemented in my app.
public class LoginActivity extends AppCompatActivity {
private TextInputLayout mLoginEmail;
private TextInputLayout mLoginPassword;
private ProgressDialog mLoginProgress;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference jLoginDatabase, student_token_reference, lecturer_token_reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mLoginProgress = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
String uid = mAuth.getCurrentUser().getUid();
fDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
fDatabase.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(uid.equals(dataSnapshot.child("key"))
{
// Open Student Activity
}
else
{
// Open Lecturers Activity
}
}
I am unaware of your database collections. So take them appropriately.
If you use the FirebaseAuth + FirebaseDatabase you can do it picking the type of the user. So in your model add the String type attribute. When the user login is not null check:
if(user.getType().equals("student1")){
startActivity(intentStudent1);
} else if(user.getType().equals("student2")){
startActivity(intentStudent2);
}
And the fathers tree of your database will be the email of the student, I use it in my app mayking it in Base64 code/uncode so the email elaine#gmail.com will be ZWxhaW5lQGdtYWlsLmNvbQ==.
I use it to get the status...

Android App crashes when trying to store 3 strings from a child on a Firebase database when trying to read strings. No Authentication yet

I've already set up Firebase with the app using Tools -> Firebase and added the internet access to manifest.
I'm trying to just get the strings from the child to be saved on the app so I can use them later on when I develop it further. I dont care about authentication yet so userID process is irrelevant as far as I gathered. The first part of the main file has the writing side and when everything else is commented out the app runs and works fine. So the problem is with reading.
What the Firebase Database looks like right now
// MainActivity.java:
public class MainActivity extends AppCompatActivity {
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference("Strings");
Button sendBtn = (Button) findViewById(R.id.sendBtn);
EditText stringText = (EditText) findViewById(R.id.stringText);
TextView textView = (TextView) findViewById(R.id.textView);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
myRef.setValue("I can send text to this from Android App");
}
});
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {
StringExchange stringX = new StringExchange();
stringX.setPhoneNum(dataSnapshot.getValue(StringExchange.class).getPhoneNum());
stringX.setTrapID(dataSnapshot.getValue(StringExchange.class).getTrapID());
stringX.setActive(dataSnapshot.getValue(StringExchange.class).getActive());
Toast.makeText(getBaseContext(), "Strings Saved", Toast.LENGTH_SHORT).show();
}
}
// class: StringExchange.java:
package com.snaresense.firebase;
/**
* Created by Kevin on 10/21/2017.
*/
public class StringExchange {
String PhoneNum;
String Active;
String TrapID;
public StringExchange(){
}
public String getPhoneNum(){
return PhoneNum;
}
public void setPhoneNum(String PhoneNum){
this.PhoneNum = PhoneNum;
}
public String getActive(){
return Active;
}
public void setActive(String Active){
this.Active = Active;
}
public String getTrapID(){
return TrapID;
}
public void setTrapID(String TrapID){
this.TrapID = TrapID;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String Active = dataSnapshot.child("snaresense").child("strings").child("StringActive").getValue(String.class);
String BatteryLevel = dataSnapshot.child("snaresense").child("strings").child("StringBatteryLevel").getValue(String.class);
String TrapId = dataSnapshot.child("snaresense").child("strings").child("StringTrapId").getValue(String.class);
String fireData = ("Hello. Trap: "+TrapId+" has been activated. The battery level is: "+BatteryLevel);
String usrnum = dataSnapshot.child("snaresense").child("strings").child("StringPhoneNum").getValue(String.class);
sendMsg (usrnum, fireData);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The reading part works and the sendMsg part is just for sending text messages with the final app.
Your showData function is bit messed up. Try changing it to:
private void showData(DataSnapshot dataSnapshot) {
StringExchange stringX = dataSnapshot.getValue(StringExchange.class);
Toast.makeText(this, "Strings Saved", Toast.LENGTH_SHORT).show();
}
If it still doesn't work, please elaborate what is the exact problem? Is it crashing? If yes then share the log. If its not working as expected then explain whats not working.

Categories

Resources