Registration Page does not record user data with Firebase - android

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());
}
}

Related

Unable to add user details on Firebase RealTime Database

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
}

User profile isn't working. Only e-mail is showing

I was trying to show user's profile in an activity. But when I try to do this, it only shows email. Name, photo, phone number is not showing. How can I show all the field of current user?I
I tried
getCurrentuser()
to get current user info and set them in the field. But it is not showing all the field.
SignUp.java
private EditText signUpnameId, signUpemailId,signUppasswordId,signUpPhoneId;
private Button signup_btn;
private TextView signUpSignIn;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private ImageView signUpimageView;
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
private DatabaseReference mDatabase;
private Uri imageUri;
private String imageurl;
private static final int IMAGE_REQUEST = 1;
private StorageReference storageReference,imagename;
private StorageTask uploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
this.setTitle("Sign Up Here");
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbarId);
signUpnameId = findViewById(R.id.signUpnameId);
signUpemailId = findViewById(R.id.signUpemailId);
signup_btn = findViewById(R.id.signup_btn);
signUpSignIn = findViewById(R.id.signUpSignIn);
signUppasswordId = findViewById(R.id.signUppasswordId);
signUpimageView =findViewById(R.id.signUpImageId);
signUpPhoneId = findViewById(R.id.signUpphoneId);
mDatabase = FirebaseDatabase.getInstance().getReference("Users");
storageReference = FirebaseStorage.getInstance().getReference("usersImage");
signUpSignIn.setOnClickListener(this);
signup_btn.setOnClickListener(this);
signUpimageView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.signup_btn:
userRegister();
break;
case R.id.signUpSignIn:
Intent intent = new Intent(getApplicationContext(),LogIn.class);
startActivity(intent);
break;
case R.id.signUpImageId:
if(uploadTask != null && uploadTask.isInProgress())
{
Toast.makeText(getApplicationContext(),"Upload in process.",Toast.LENGTH_SHORT).show();
}else {
showPictureDialog();
}
}
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(galleryIntent, GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY && data != null && data.getData() != null ) {
imageUri = data.getData();
try {
Picasso.get().load(imageUri).into(signUpimageView);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
private String getFileExtension(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void userRegister() {
final String name = signUpnameId.getText().toString();
final String email = signUpemailId.getText().toString().trim();
final String password = signUppasswordId.getText().toString().trim();
final String phoneNum = signUpPhoneId.getText().toString();
if(email.isEmpty())
{
signUpemailId.setError("Enter an email address");
signUpemailId.requestFocus();
return;
}
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
signUpemailId.setError("Enter a valid email address");
signUpemailId.requestFocus();
return;
}
//checking the validity of the password
if(password.isEmpty())
{
signUppasswordId.setError("Enter a password");
signUppasswordId.requestFocus();
return;
}
if(password.length() < 6)
{
signUppasswordId.setError("Password is too short. Password Should be more than 6");
signUppasswordId.requestFocus();
return;
}
//checking the validity of the password
if(name.isEmpty())
{
signUpnameId.setError("Enter a Name");
signUpnameId.requestFocus();
return;
}
if(imageUri == null)
{
signUpSignIn.setError("Please select an image first");
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful())
{
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
final StorageReference Imagename = storageReference.child("image"+imageUri.getLastPathSegment());
imageurl = imageUri.toString();
Imagename.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),"Place added Done!",Toast.LENGTH_SHORT).show();
Task<Uri> uriTask = taskSnapshot.getMetadata().getReference().getDownloadUrl();
while(!uriTask.isSuccessful());
Uri downloadUrl = uriTask.getResult();
UserInfo userInfo = new UserInfo(name,email,phoneNum,downloadUrl.toString());
String uploadId = mDatabase.push().getKey();
mDatabase.child(uploadId).setValue(userInfo);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
else
{
Toast.makeText(getApplicationContext(),"Error: "+task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
if(task.getException() instanceof FirebaseAuthUserCollisionException)
{
Toast.makeText(getApplicationContext(),"Already registered",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Eroor: "+ task.getException(),Toast.LENGTH_SHORT).show();
}
}
}
});
}
Profile.Java
private ImageView profileImageview;
private TextView profilenameview,profileemailview, profilephoneview;
private Button profilesignoutbtn;
private FirebaseUser firebaseUser;
private FirebaseAuth mAuth;
private FirebaseDatabase firebaseDatabase;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
profileImageview = findViewById(R.id.profileImageView);
profileemailview = findViewById(R.id.profileemailview);
profilenameview = findViewById(R.id.profilenameview);
profilephoneview = findViewById(R.id.profilephoneview);
progressBar = findViewById(R.id.progressbarproId);
profilesignoutbtn = findViewById(R.id.profilesignout_btn);
profilesignoutbtn.setOnClickListener(this);
// Initialize Firebase Auth
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Image");
mAuth = FirebaseAuth.getInstance();
String userKey = user.getUid();
databaseReference.child("Profile");
databaseReference.child(userKey);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("users").getValue(String.class);
profilenameview.setText(user.getDisplayName());
profileemailview.setText(user.getEmail());
Picasso.get().load(user.getPhotoUrl()).into(profileImageview);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
UserInfo.java
public class UserInfo{
String name,email,phoneNum,imageurl;
public UserInfo(String name, String email, String phoneNum, String imageurl) {
this.name = name;
this.email = email;
this.phoneNum = phoneNum;
this.imageurl = imageurl;
}
public UserInfo(String name, String email, String phoneNum, Uri uri) {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
}
Android studio is showing that
sendEmailVerification()
may produce NullPointerException. Besides
getReference()
and
getDownloadUrl()
also may produce NullPOinterException.How can I solve every issues and correctly get the expected output? Here is a screenshot of profile.
You aren't actually defining the name of the user ,
Use this in onCompleteListener method of firebase auth
new UserProfileChangeRequest.Builder()
.setDisplayName(nameUser)
.build();

How to fix NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.rsolveapp.User.getEmail()'

I'm trying to retrieve data from current logged in user from my firebase realtime database, but when i go into activity that suppose to show the data, the app crash with the following error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.rsolveapp.User.getEmail()' on a null object reference"
This is the activity for showing the data
public class RsolverAccount extends AppCompatActivity {
TextView showEmail;
private static final String TAG = RsolverAccount.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rsolveraccount);
setWidget();
showData();
}
private void showData () {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if(firebaseUser != null) {
String email = firebaseUser.getEmail();
Log.d(TAG, email);
}
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference().child("sraboetapp").child("userdesc").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
showEmail.setText(user.getEmail());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDatabase.addValueEventListener(postListener);
}
public void setWidget() {
showEmail = (TextView) findViewById(R.id.showEmail);
}
}
This is my User class
public class User implements Serializable{
private String email;
private String name, pass, id, phone;
private String key;
public User(){
}
public String getKey(){
return key;
}
public void setKey(String key){
this.key=key;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email=email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getPass(){
return pass;
}
public void setPass(String pass){
this.pass=pass;
}
public String getId(){
return id;
}
public void setId(String id){
this.id=id;
}
public String getPhone(){
return phone;
}
public void setPhone(String phone){
this.phone=phone;
}
#Override
public String toString(){
return " "+email+"/n"+
" "+name+"/n"+
" "+pass+"/n"+
" "+id+"/n"+
" "+phone;
}
public User(String Remail, String Rname, String Rpass, String Rid, String Rphone){
this.email=Remail;
this.name=Rname;
this.pass=Rpass;
this.id=Rid;
this.phone=Rphone;
}
}
This is my database structure
{
"description" : {
"-LpJNvsR3oIGA5pv1uOK" : {
"day" : "2",
"description" : "tes",
"eHour" : "12",
"eMin" : "12",
"sHour" : "12",
"sMin" : "12"
}
},
"userdesc" : {
"-LquV8N1AJbRdhSKMA2T" : {
"email" : "bryan5#gmail.com",
"id" : "870788464845",
"name" : "bry5",
"pass" : "123456",
"phone" : "484854484546"
}
}
}
This is how i insert the data
private void RegisterUser() {
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String emailUser = e1.getText().toString().trim();
String passwordUser = e3.getText().toString().trim();
String name1 = e2.getText().toString();
String id = e5.getText().toString();
String phone = e6.getText().toString();
if (emailUser.isEmpty()){
e1.setError("Email tidak boleh kosong");
}
// jika email not valid
else if (!Patterns.EMAIL_ADDRESS.matcher(emailUser).matches()){
e1.setError("Email tidak valid");
}
// jika password kosong
else if (passwordUser.isEmpty()){
e3.setError("Password tidak boleh kosong");
}
//jika password kurang dari 6 karakter
else if (passwordUser.length() < 6){
e3.setError("Password minimal terdiri dari 6 karakter");
}
else {
//create user dengan firebase auth
auth.createUserWithEmailAndPassword(emailUser,passwordUser)
.addOnCompleteListener(Register.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//jika gagal register do something
if (!task.isSuccessful()){
Toast.makeText(Register.this,
"Register gagal karena "+ task.getException().getMessage(),
Toast.LENGTH_LONG).show();
}
else {
//jika sukses akan menuju ke login activity
if(!isEmpty(e1.getText().toString()) && !isEmpty(e2.getText().toString()) && !isEmpty(e3.getText().toString()) && !isEmpty(e5.getText().toString())&& !isEmpty(e6.getText().toString())) {
submitUser(new User(e1.getText().toString(), e2.getText().toString(), e3.getText().toString(), e5.getText().toString(), e6.getText().toString()));
//Toast.makeText(this,"Wassup",Toast.LENGTH_SHORT).show();
/*startActivity(new Intent(MainActivity.this,MainActivity2.class));*/
//EditText etLocation = (EditText) findViewById(R.id.desc);
SharedPreferences sharedPref = getSharedPreferences("myuser", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("user", emailUser);
editor.apply();
Intent intent = new Intent(Register.this, MainActivity.class);
//intent.putExtra("location", etLocation.getText().toString());
startActivity(intent);
}
else{
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
e1.getWindowToken(), 0);
}
}
}
});
}
}
});
}
private boolean isEmpty(String s) {
return TextUtils.isEmpty(s);
}
private void submitUser(User user) {
database.child("userdesc").push().setValue(user).addOnSuccessListener(this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
e1.setText("");
e2.setText("");
e3.setText("");
e4.setText("");
e5.setText("");
e6.setText("");
}
});
}
It seems like there is no valid User object in the data you're processing.
Your JSON is using push IDs for the child nodes under that, while your code is loading from FirebaseAuth.getInstance().getCurrentUser().getUid(). If you want to load the users by their UID, you should store them under their UID, with something like:
mDatabase = FirebaseDatabase.getInstance().getReference().child("sraboetapp").child("userdesc").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
mDatabase.setValue(user);
Based on the code you added to your question submitUser should be:
private void submitUser(User user) {
database.child("userdesc").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user).addOnSuccessListener(this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
e1.setText("");
e2.setText("");
e3.setText("");
e4.setText("");
e5.setText("");
e6.setText("");
}
});
}

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());
}
});
}

android firebase database save data for current user

I have an app that send sms templates with firebase user login.
I want to save sms logs for each user on firbase database so I will be able to see what messages each user sent. I have no idea how to make it probably ..
my code
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private ProgressBar spinner;
EditText EMAIL, PASSWORD;
Button SIGNIN;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
EMAIL = (EditText) findViewById(R.id.email);
PASSWORD = (EditText) findViewById(R.id.password);
SIGNIN = (Button) findViewById(R.id.login);
spinner = (ProgressBar) findViewById(R.id.progressBar1);
spinner.setVisibility(View.GONE);
SIGNIN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ((TextUtils.isEmpty(EMAIL.getText().toString())) && (TextUtils.isEmpty(PASSWORD.getText().toString()))) {
Toast.makeText(getApplicationContext(), "make sure that you enter full ogin info ", Toast.LENGTH_SHORT).show();
}else if (!isEmailValid(EMAIL.getText().toString())){
Toast.makeText(getApplicationContext(), "enter a valid mail", Toast.LENGTH_SHORT).show();
} else {
SignIn(EMAIL.getText().toString(), PASSWORD.getText().toString());
}
}
});
SIGNIN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pass = PASSWORD.getText().toString();
if(TextUtils.isEmpty(pass)) {
PASSWORD.setError("kindly enter password ");
return;
}
if ((TextUtils.isEmpty(EMAIL.getText().toString())) && (TextUtils.isEmpty(PASSWORD.getText().toString()))) {
Toast.makeText(getApplicationContext(), "wrong info", Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
} else {
spinner.setVisibility(View.VISIBLE);
SignIn(EMAIL.getText().toString(), PASSWORD.getText().toString());
}
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
}
};
mAuth.addAuthStateListener(mAuthListener);
}
private void SignIn(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
finish();
Toast.makeText(getApplicationContext(), "login done",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
Toast.makeText(getApplicationContext(), "Error username",
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
}
});
}
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
}
sms.java
public class Harsh extends AppCompatActivity {
RadioButton lo, hi, mid;
String sense;
Button submit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.harsh_layout);
lo = (RadioButton) findViewById(R.id.lo_btn);
hi = (RadioButton) findViewById(R.id.hi_btn);
mid = (RadioButton) findViewById(R.id.mid_btn);
submit = (Button) findViewById(R.id.submitButton);
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
final String num = prefs.getString("nameKey", "0");
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lo.isChecked()) {
sendSMS( num, " message one");
} else if (hi.isChecked()) {
sendSMS( num, " message 2");
// for example save this message for current logged user
} else if (mid.isChecked()) {
sendSMS( num, " message 3");
}
Toast.makeText(getApplicationContext(), "Command Sent", Toast.LENGTH_LONG).show(); // print the value of selected super star
}
});
}
public void sendSMS(String phoneNo, String msg) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, msg, null, null);
Toast.makeText(getApplicationContext(), "Command Sent",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
}
after alot of researches i found that set and get class and i modify my code as below
public class Post {
private String message;
private String number;
private String user;
private String date;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
then in activity that i need to Post data to firbase database i add that simple code
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference posts = database.getReference("Messages:");
//this code for keep posts even app offline until the app online again
posts.keepSynced(true);
Post post = new Post();
post.setMessage("Messsage");
post.setUser(name);
post.setNumber(num);
post.setDate(s);
posts.push().setValue(post);

Categories

Resources