Unable to add user details on Firebase RealTime Database - android

I am currently trying to add user details who have registered in my app using Firebase Phone authentication to Firebase Real time database. I am successfully able to verify a user, but I am not able to send to Details Activity class where I need the user to enter his details, instead I jump to MainActivity Directly.
I do get Toast "Phone Verified" whenever I add a new user.
Register.java
public class Register extends AppCompatActivity {
FirebaseAuth auth;
String phoneNumber;
String otpCode;
String verificationId;
EditText phone, optEnter;
Button next;
CountryCodePicker countryCodePicker;
PhoneAuthCredential credential;
Boolean verificationOnProgress = false;
ProgressBar progressBar;
TextView state, resend;
PhoneAuthProvider.ForceResendingToken token;
//FirebaseFirestore fStore;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
phone = findViewById(R.id.phone);
optEnter = findViewById(R.id.codeEnter);
countryCodePicker = findViewById(R.id.ccp);
next = findViewById(R.id.nextBtn);
auth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
state = findViewById(R.id.state);
resend = findViewById(R.id.resendOtpBtn);
resend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// todo:: resend OTP
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!phone.getText().toString().isEmpty() && phone.getText().toString().length() == 10) {
if (!verificationOnProgress) {
next.setEnabled(false);
progressBar.setVisibility(View.VISIBLE);
state.setVisibility(View.VISIBLE);
String phoneNum = "+" + countryCodePicker.getSelectedCountryCode() + phone.getText().toString();
Log.d("phone", "Phone No.: " + phoneNum);
requestPhoneAuth(phoneNum);
} else {
next.setEnabled(false);
optEnter.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
state.setText("Logging in");
state.setVisibility(View.VISIBLE);
otpCode = optEnter.getText().toString();
if (otpCode.isEmpty()) {
optEnter.setError("Required");
return;
}
credential = PhoneAuthProvider.getCredential(verificationId, otpCode);
verifyAuth(credential);
}
} else {
phone.setError("Valid Phone Required");
}
}
});
}
private void requestPhoneAuth(String phoneNumber) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(phoneNumber, 60L, TimeUnit.SECONDS, this,
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeAutoRetrievalTimeOut(String s) {
super.onCodeAutoRetrievalTimeOut(s);
Toast.makeText(Register.this, "OTP Timeout, Please Re-generate the OTP Again.", Toast.LENGTH_SHORT).show();
resend.setVisibility(View.VISIBLE);
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
token = forceResendingToken;
verificationOnProgress = true;
progressBar.setVisibility(View.GONE);
state.setVisibility(View.GONE);
next.setText("Verify");
next.setEnabled(true);
optEnter.setVisibility(View.VISIBLE);
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
verifyAuth(phoneAuthCredential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(Register.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void verifyAuth(PhoneAuthCredential credential) {
auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(Register.this, "Phone Verified", Toast.LENGTH_SHORT).show();
checkUserProfile();
} else {
progressBar.setVisibility(View.GONE);
state.setVisibility(View.GONE);
Toast.makeText(Register.this, "Can not Verify phone and Create Account.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if (auth.getCurrentUser() != null) {
progressBar.setVisibility(View.VISIBLE);
state.setText("Logging IN");
state.setVisibility(View.VISIBLE);
checkUserProfile();
}
}
private void checkUserProfile() {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
if (userid != null) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(Register.this, "Profile doesnt exist", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Register.this, Details.class);
startActivity(intent);
}
}
}
Details.java
public class Details extends AppCompatActivity {
public static final String TAG = "TAG";
EditText firstName,lastName,email;
Button saveBtn;
FirebaseAuth auth;
FirebaseFirestore fStore;
String userID;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
firstName = findViewById(R.id.firstName);
lastName = findViewById(R.id.lastName);
email = findViewById(R.id.emailAddress);
saveBtn = findViewById(R.id.saveBtn);
auth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String First_Name= firstName.getText().toString();
String Last_Name= lastName.getText().toString();
String EMail= email.getText().toString();
if(firstName.getText().toString().isEmpty()||lastName.getText().toString().isEmpty() || email.getText().toString().isEmpty()){
Toast.makeText(Details.this, "Fill the required Details", Toast.LENGTH_SHORT).show();
return;
}
register(First_Name,Last_Name,EMail);
}
});
}
private void register(String first_name, String last_name, String eMail) {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
Map<String,Object> hashmap=new HashMap<>();
hashmap.put("First Name",first_name);
hashmap.put("Last Name",last_name);
hashmap.put("Email-Id",eMail);
reference.setValue(hashmap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent=new Intent(Details.this,MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(Details.this,"Registration failed...",Toast.LENGTH_SHORT).show();
}
}
});
}
}

It seems that in your Register class in checkUserProfile() function you are checking if userId from firebaseUser.getUid() is not null. At the moment this will always be not null, because you are already asserting that the user must be authenticated at this point.
Judging from your code this is just a mistake on your part. I assume that what you are trying to do is actually see if the details already exist in the FirebaseDatabase. You have a reference to the database which you are not using.
private void checkUserProfile() {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
//Unused reference
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
if (userid != null) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
}
But also my question would be, are you sure you want to use Realtime Database for user details? You are saving details in Details function using FirebaseFirestore. Didn't you want to check if the details already exist in FirebaseFirestore?
How to fix:
First, let's create the user data class:
public class User {
public String uid;
public String firstName;
public String lastName;
public String email;
public User {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String uid, String firstName, String lastName, String email) {
this.uid = uid;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
}
Now, let's change the code in Details.java class to use User class:
private void register(String first_name, String last_name, String eMail) {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
User user = new User(userid, firstName, lastName, eMail)
reference.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent=new Intent(Details.this,MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(Details.this,"Registration failed...",Toast.LENGTH_SHORT).show();
}
}
});
}
Let's check if the registration details exist in the database in checkUserProfile() method:
private void checkUserProfile() {
FirebaseUser firebaseUser = auth.getCurrentUser();
assert firebaseUser != null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Intent intent = new Intent(Register.this, MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(Register.this, "Profile doesnt exist", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Register.this, Details.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
Let me know if it works for you.

Firebase will generate a single unique key(UID) on registration of account whether using Email/Phone number. This key remains associated with that account until the account exists in the firebase authentication list.
So, once you register with some number/email at that time UID is created for the same. every time you fetch UID it will return that user UID, and you are also asserting Firebase User is NotNull So, every time you got UID from firebase and app move to the dashboard screen.
If you want to move users to a Detail screen then. You can also add a condition based on firebase User.
if(firebaseUser != null){
// Get UID and Move to Dashboard
}else{
// Move to Detail Screen
}

Related

Firebase doesn't register new users

I have a problem, I can't register in my chat app. It shows me that "You can't register". I don't know where is the problem. I set read and write to true in my database but it still not working. I use the last versions of Firebase. I haven't problems with the internet and connected firebase to my project successfully.
This is my register activity
MaterialEditText username, email, password;
Button btn_register;
FirebaseAuth auth;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Регистрация");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
username = findViewById(R.id.username);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
btn_register = findViewById(R.id.btn_register);
auth = FirebaseAuth.getInstance();
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_username = username.getText().toString();
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
if (TextUtils.isEmpty(txt_username) || TextUtils.isEmpty(txt_email) || TextUtils.isEmpty(txt_password)) {
Toast.makeText(RegisterActivity.this, "Write more", Toast.LENGTH_SHORT).show();
} else if (txt_password.length() < 6 ){
Toast.makeText(RegisterActivity.this, "Password too short ", Toast.LENGTH_SHORT).show();
} else {
register(txt_username, txt_email, txt_password);
}
}
});
}
private void register(final String username, String email, String password){
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
FirebaseUser firebaseUser= auth.getCurrentUser();
assert firebaseUser !=null;
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
HashMap<String, String> HashMap = new HashMap<>();
HashMap.put("id", userid);
HashMap.put("username", username);
HashMap.put("imageURL", "default");
reference.setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
});
}else {
Toast.makeText(RegisterActivity.this, "You cant register", Toast.LENGTH_SHORT).show();
}
}
});
}
}
When initializing your FirebaseDatabase reference, the item node with the provided user id does not exist yet in your database thus the reference is null
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
Instead, initialize the reference to the Users node
String userid = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference("Users");
Then when saving the user's data you can save to their userId:
reference.child(userid).setValue(HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
...
});
in manifest file allow internet permission. if you continue this err create failure listener and print failure code
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();

Can't pass null for argument 'pathString' in child() at com.google.firebase.database.DatabaseReference.child(Unknown Source:40) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am creating an android app to login the users by using Mobile number OTP verification from fire-base This is how the database looks like
This is the loggin activity where i am passing the value "mobile" to OTP typing activity( here LoginActivity.java)
CardView card_view = findViewById(R.id.cardView);
card_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mobile = editTextMobile.getText().toString().trim();
if(mobile.isEmpty() || mobile.length() < 10){
editTextMobile.setError("Enter a valid mobile");
editTextMobile.requestFocus();
return;
}
if(mobile.length()>10)
{
editTextMobile.setError("Enter a valid mobile");
editTextMobile.requestFocus();
return;
}
Intent intent = new Intent(LoginActivity.this, VerifyPhoneActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
}
});
This is where user will enter the OTP (VerifyPhoneActivity.java). If the OTP is correct and if the mobile number is not exist in database already then user can go to sigh up up activity
public FirebaseAuth.AuthStateListener authListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth= FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
sendVerificationCode();
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifySignInCode();
}
});
}
private void verifySignInCode()
{
final EditText fd = (EditText) findViewById(R.id.et1);
String value= fd.getText().toString();
final EditText sd = (EditText) findViewById(R.id.et2);
String value1= sd.getText().toString();
// int finalValue1=Integer.parseInt(value1);
EditText td = (EditText) findViewById(R.id.et3);
String value2= td.getText().toString();
EditText fod = (EditText) findViewById(R.id.et4);
String value3= fod.getText().toString();
EditText fid = (EditText) findViewById(R.id.et5);
String value4= fid.getText().toString();
EditText sid = (EditText) findViewById(R.id.et6);
String value5= sid.getText().toString();
code = value + value1+value2+value3+value4+value5;
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codesent, code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
FirebaseUser userid = FirebaseAuth.getInstance().getCurrentUser();
final String uid = userid.getUid();
ref.child("Users");
ref.child(mobile).child(uid);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "already account there",
Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent(VerifyPhoneActivity.this, Signup.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
Intent myIntent = new Intent(VerifyPhoneActivity.this, Signup.class);
startActivity(myIntent);
Toast.makeText(getApplicationContext(), "account not exist",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(getApplicationContext(), "login success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "login faild",
Toast.LENGTH_LONG).show();
// Sign in failed, display a message and update the UI
// Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
Toast.makeText(getApplicationContext(), "OTP was wrong",
Toast.LENGTH_LONG).show();
}
}
}
});
}
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks=new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
Toast.makeText(getApplicationContext(), "verification completed",
Toast.LENGTH_LONG).show();
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(getApplicationContext(), "sending faild"+e,
Toast.LENGTH_LONG).show();
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
// super.onCodeSent(s, forceResendingToken);
Toast.makeText(getApplicationContext(), "sent",
Toast.LENGTH_LONG).show();
codesent=s;
}
};
private void sendVerificationCode() {
Intent intent = getIntent();
mobile = intent.getStringExtra("mobile");
Toast.makeText(getApplicationContext(), mobile,
Toast.LENGTH_LONG).show();
String phonenumber= "+91"+mobile;
// Toast.makeText(getApplicationContext(), phonenumber,
// Toast.LENGTH_LONG).show();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phonenumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
}
And at last this is where (Signup.java) am getting error (i will mension below)
public class Signup extends Activity {
String name;
String address;
String pincode;
String city;
String mobile;
DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
Intent intent = getIntent();
mobile = intent.getStringExtra("mobile");
findViewById(R.id.signupbutton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText nameedittext = (EditText) findViewById(R.id.nametextview);
name= nameedittext.getText().toString();
EditText addressedittext = (EditText) findViewById(R.id.addresstextview);
address= addressedittext.getText().toString();
EditText pincodeedittext = (EditText) findViewById(R.id.picodetextview);
pincode= pincodeedittext.getText().toString();
EditText cityedittext = (EditText) findViewById(R.id.citytextview);
city= cityedittext.getText().toString();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref = ref.child("Users");
FirebaseUser userid = FirebaseAuth.getInstance().getCurrentUser();
final String uid = userid.getUid();
ref = ref.child(mobile).child(uid);
Map<String, String> userData = new HashMap<String, String>();
userData.put("Name", name);
userData.put("Address", address);
userData.put("Pin", pincode);
userData.put("City", city);
ref.setValue(userData);
}
});
}
}
I am facing 2 problems
I am getting the error below and app crashes app relaunching the same activity (Signup.java) if i enter the details again it will get updated in db as screenshot above (in case i am the first user)
If the first user signed up and his mobile got registered then when the second user sign up it is showing "login success" and account "already there" 2 toasts
Error am getting
2019-03-15 16:57:40.706 1932-1932/com.example.meenvandi E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.meenvandi, PID: 1932
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.google.firebase.database.DatabaseReference.child(Unknown Source:40)
at com.example.meenvandi.Signup$1.onClick(Signup.java:78)
at android.view.View.performClick(View.java:6330)
at android.view.View$PerformClick.run(View.java:25136)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:192)
at android.app.ActivityThread.main(ActivityThread.java:6778)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:875)
I am just starting android and this project is very very impotent for me please help if i you can identify the problem which i am unable to
One of the variables are null, its either mobile or uid, you can try to print both variables out to know which one is null.
My guess is you are trying to save a user in the db and this user haven't logged in to firebase before so uid will be null

Changing shared preference value to null for other logins

So my concern is that I am using Shared Preference to store Name in android and can also retrieve the same when logged in again.But, when some other person logs in from the same device, still the name stored is of the previous user. How can I change this and fetch the value of the New user name from firebase? P.S I am new to Android
Following is my code for Manual Login:-
public class ManualLogin extends AppCompatActivity implements View.OnClickListener{
private Button buttonRegister;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignup;
private EditText editTextName;
DatabaseReference databaseUsers;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
private static final String TAG = "FACELOG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_login);
databaseUsers = FirebaseDatabase.getInstance().getReference("Users");
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser()!=null){
//profile activity here
finish();
startActivity(new android.content.Intent(getApplicationContext(), AccountActivity.class));
}
progressDialog = new ProgressDialog(this);
buttonRegister = (Button)findViewById(R.id.buttonRegister);
editTextEmail = (EditText)findViewById(R.id.editTextEmail);
editTextPassword = (EditText)findViewById(R.id.editTextPassword);
editTextName = (EditText)findViewById(R.id.editTextName);
textViewSignup = (TextView)findViewById(R.id.textViewSignup);
buttonRegister.setOnClickListener(this);
textViewSignup.setOnClickListener(this);
}
public void registerUser() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
final String name = editTextName.getText().toString().trim();
if(!TextUtils.isEmpty(name)) {
String id = databaseUsers.push().getKey();
Users users = new Users(id, name);
databaseUsers.child(id).setValue(users);
//Toast.makeText(this, "User Created", Toast.LENGTH_SHORT).show();
}else{
//email is empty
Toast.makeText(this, "Enter Name", Toast.LENGTH_SHORT).show();
//stop function execution
return;
}
if(TextUtils.isEmpty(email)){
//email is empty
Toast.makeText(this, "Enter Email id", Toast.LENGTH_SHORT).show();
//stop function execution
return;
}
if(TextUtils.isEmpty(password)){
//password is empty
Toast.makeText(this, "Enter Password", Toast.LENGTH_SHORT).show();
//stop function execution
return;
}
//if validations are fine
//show progressBar
progressDialog.setMessage("Registering User...");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//user is successfully registered & logged in
//profile activity here
finish();
startActivity(new android.content.Intent(getApplicationContext(), AccountActivity.class));
userProfile();
Toast.makeText(ManualLogin.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ManualLogin.this, "Failed to Register", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
SharedPreferences sharedPref = getSharedPreferences("userName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", editTextName.getText().toString());
editor.commit();
//Toast.makeText(ManualLogin.this, "Name Saved", Toast.LENGTH_SHORT).show();
}
});
}
//set User Display name
private void userProfile(){
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(editTextName.getText().toString().trim()).build();
user.updateProfile(profileUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.d("Testing", "User Profile Updated");
}
}
});
}
}
#Override
public void onClick(View v) {
if(v == buttonRegister){
registerUser();
}
if(v == textViewSignup){
//open login activity
finish();
startActivity(new android.content.Intent(this, LoginActivity.class));
}
}
}
Below is the code for AccountActivity:-
public class AccountActivity extends AppCompatActivity {
private Button logout;
private TextView textViewUserName;
private FirebaseAuth mAuth;
private FirebaseAuth firebaseAuth;
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
logout = (Button)findViewById(R.id.logout);
textViewUserName = (TextView)findViewById(R.id.textViewUserName);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this, LoginActivity.class));
}
FirebaseUser sname = firebaseAuth.getCurrentUser();
textViewUserName.setText("Welcome "+ sname.getDisplayName());
SharedPreferences sharedPref = getSharedPreferences("userName", Context.MODE_PRIVATE);
String name = sharedPref.getString("name", "");
textViewUserName.setText("Welcome "+ name);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
LoginManager.getInstance().logOut();
updateUI();
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
updateUI();
}
}
private void updateUI() {
Toast.makeText(this, "You have Logged out", Toast.LENGTH_SHORT).show();
Intent accountIntent = new Intent(this, MainActivity.class);
startActivity(accountIntent);
finish();
}
}
when you login that time store data into sharedpreference like below
private void saveData(String value){
SharedPreferences sharedPreferences=getSharedPreferences("MyData",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("User",value);
editor.commit();
}
In read new user data into firebase database.
private void readData() {
// define only root node.
mFirebaseDatabase.child("User").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
User user = dataSnapshot.getValue(User.class);
mEtPwd.setText(user.pwd);
mEtName.setText(user.name);
mEtEmail.setText(user.email);
saveData(user.name);
// }
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
}

Registration Page does not record user data with Firebase

public class RegisterActivity extends AppCompatActivity {
//create variables
private EditText mUsername, mPassword, mEmail, mPhone;
private Button mRegister;
private TextView mLogin;
private FirebaseAuth mAuth;
private ImageView mProfilePicture;
String user_email, user_name, user_phone, user_password;
//on creation of activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
setupViews();
//firebase instance declared
mAuth = FirebaseAuth.getInstance();
//When register is clicked
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if all fields are okay using validation method
if(validate()){
//get user info
String user_email = mEmail.getText().toString().trim();
String user_password = mPassword.getText().toString().trim();
String user_phone = mPhone.getText().toString().trim();
String user_name = mUsername.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(user_email, user_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
sendEmailVerification();
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(RegisterActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}else{
Toast.makeText(RegisterActivity.this, "Registration Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
//Return user back to login page
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}
});
}
//setup views by id from xml
private void setupViews(){
mUsername = (EditText)findViewById(R.id.editTextNewUsername);
mPassword = (EditText)findViewById(R.id.editTextNewPassword);
mEmail = (EditText)findViewById(R.id.editTextNewEmail);
mPhone = (EditText)findViewById(R.id.editTextPhone);
mRegister = (Button)findViewById(R.id.buttonRegister);
mLogin = (TextView)findViewById(R.id.textViewLogin);
mProfilePicture = (ImageView)findViewById(R.id.imageViewProfilePicture);
}
//validate if all fields are okay and not empty
private Boolean validate() {
Boolean result = false;
//convert inputs to strings
String user_name = mUsername.getText().toString();
String user_password = mPassword.getText().toString();
String user_email = mEmail.getText().toString();
String user_phone = mPhone.getText().toString();
//check if any fields are empty, if not then return result
if (user_name.isEmpty() || user_password.isEmpty() || user_email.isEmpty() || user_phone.isEmpty()) {
Toast.makeText(this, "All fields are required for registration.", Toast.LENGTH_SHORT).show();
} else {
result = true;
}
return result;
}
private void sendEmailVerification(){
FirebaseUser firebaseUser = mAuth.getCurrentUser();
if(firebaseUser!=null){
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserData();
Toast.makeText(RegisterActivity.this, "Successfully Registered, Verification mail sent!", Toast.LENGTH_SHORT).show();
mAuth.signOut();
finish();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}else{
Toast.makeText(RegisterActivity.this, "Verification mail has'nt been sent!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void sendUserData(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference(mAuth.getCurrentUser().getUid());
UserProfile userProfile = new UserProfile(user_phone, user_email, user_name);
myRef.setValue(userProfile);
}
}
Solved the crash with my profile page and got it to save artifical data, but found out my registration page is the problem and is not recording data. Here is my Userprofile.java for reference
public class UserProfile {
public String user_phone;
public String user_email;
public String user_name;
public UserProfile() {
}
public UserProfile(String user_phone, String user_email, String user_name) {
this.user_phone = user_phone;
this.user_email = user_email;
this.user_name = user_name;
}
public String getUser_phone() {
return user_phone;
}
public void setUser_phone(String user_phone) {
this.user_phone = user_phone;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
Any help would be appreciated, i'd read extensively on the topic and can't seem to see whatever small issue is causing the hold-up. Any other pointers are also welcome.
Try changing:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
assert userProfile != null;
mProfileName.setText(userProfile.getUser_name());
mProfileNumber.setText(userProfile.getUser_phone());
mProfileEmail.setText(userProfile.getUser_email());
}
With:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
if(userProfile != null){
mProfileName.setText(userProfile.getUser_name());
mProfileNumber.setText(userProfile.getUser_phone());
mProfileEmail.setText(userProfile.getUser_email());
}
}

User login can'd identify user position

User register as student or tutor during registration which saved in firebase database but when login cannot identify the user position which saved in the firebase database so what should I do? Please anyone can give suggestion or advice me how to do this.
The database is save the uid from email authentication as the node under the root then rest details is the children of the uid.
The code like this
private FirebaseAuth auth;
private EditText un, pw;
private String getun, getpw, uid;
private Button bl;
private FirebaseDatabase db;
private DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance();
ref = db.getReference();
uid = auth.getCurrentUser().getUid();
ref = db.getReference("users").child(uid);
un = (EditText) findViewById(R.id.Lun);
pw = (EditText) findViewById(R.id.Lpw);
bl = (Button) findViewById(R.id.Lbt);
final TextView rl = (TextView) findViewById(R.id.Lreg);
//login
bl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getun = un.getText().toString().trim();
getpw = pw.getText().toString().trim();
loginaction(getun, getpw);
}
});
//open register page
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ri = new Intent(Login.this,Register.class);
Login.this.startActivity(ri);
}
});
}
private void loginaction(String a, String b){
auth.signInWithEmailAndPassword(a, b).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("Login", "Login Success" + task.isSuccessful());
if (!task.isSuccessful()) {
Log.w("Login", "Login Failed", task.getException());
Toast.makeText(Login.this, "Login Failed. Please try again", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Login.this, "Login Success", Toast.LENGTH_SHORT).show();
ref.orderByChild("position").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String ps = dataSnapshot.getValue().toString();
if(ps.equalsIgnoreCase("student")){
Intent i = new Intent(Login.this, StudentHomePage.class);
startActivity(i);
}else if (ps.equalsIgnoreCase("tutor")){
Intent i = new Intent(Login.this, TutorHomePage.class);
startActivity(i);
}else{
Toast.makeText(Login.this,
"Wrong input. Please check again the email and password.", Toast.LENGTH_SHORT).show();
return;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// ...
}
});
}
Create two child nodes from users. One for students and one for tutors.(Give both child values a value of true, otherwise firebase doesn't save the children.)
Have two registration buttons ..one for students and one for tutors. Registration for Tutor code.....
mRegistration.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(DriverLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
Toast.makeText(TutorsLoginActivity.this, "Sign in error", Toast.LENGTH_SHORT).show();
}else{
String user_id= mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db= FirebaseDatabase.getInstance().getReference().child("Users").child("Tutors").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
Do the same for the students. Just change the .child("Tutors") to .child("Students") This will give you UIDs for the two different groups. And you can do the same when logging in. I think this is a better way to proceed.

Categories

Resources