Why is createUserWithEmailAndPassword not working - android

mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email=((EditText)findViewById(R.id.email)).getText().toString();
String password=((EditText)findViewById(R.id.password)).getText().toString();
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener( new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(SignUpActivity.this,"Hooray!",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(SignUpActivity.this,"Ohhno!",Toast.LENGTH_LONG).show();
}
}
});
}
});
This is my layout file snippet
I have also enabled email password authentication in firebase.

Related

Realtime refresh after deleting data from firebase

I have a button to delete amounts, and I have a textview with total amount, but when I delete amounts the textview with the total does not update, it only does if I go to another activity and come back, why is it? any ideas?
public void onClick(View view) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Expenses").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.child(postId).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
Expense expenseBackUp = new Expense(item, category, date, postId, amount);
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Snackbar.make(rv, item + " has been deleted", Snackbar.LENGTH_LONG).setAction("UNDO", new View.OnClickListener() {
#Override
public void onClick(View view) {
reference.child(postId).setValue(expenseBackUp);
}
}).show();
} else {
Toast.makeText(ExpensesActivity.this, "Something went wrong, try again" + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
dialog.dismiss();
}

Can't resolve (Firebase)User expression expected

Just trying to make a phone authentication as per a tutorial i'm watching which I have written down the code as below, but i keep getting the error expression expected for 'User' - I am completely new to this so I imagine it's something simple I need help nonetheless! Thank you in advance!
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(this, new OnCompleteListener<Credential.UserCredential>() {
#Override
public void onComplete(#NonNull Task<Credential.UserCredential> task) {
if(task.isSuccessful())
userIsLoggedIn();
}
private void userIsLoggedIn() {
User = FirebaseAuth.getInstance().getCurrentUser();
if(User != null){
startActivity(new Intent(getApplicationContext(), MainPageActivity.class));
finish();
return;
You have a class named "User" and you didn't define its variable here which showing java expression error . Actually you are looking for User of Firebase , FirebaseAuth has class FirebaseUser . So it should be below code to check current user .
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){.....
Update (cause of new error) - You are implementing PhoneAuthCredential , but passing Username-password based Credential.UserCredential and implemeting wrong method.
Your signInWithPhoneAuthCredential void would be -
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(this , new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
userIsLoggedIn();
} else {
//
}
}
});
}
And your attached code would be -
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
//TODO
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
//TODO
}
};
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential).addOnCompleteListener(this , new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
userIsLoggedIn();
} else {
//
}
}
});
}
private void userIsLoggedIn() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
startActivity(new Intent(getApplicationContext(), MainPageActivity.class));
finish();
// return;
}
}
Please check the documentation.

How to read data from a branch in firebase

im trying to get the "type" value here (see the image)
and here is what im doing
firebaseAuth.signInWithEmailAndPassword(email , password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
DatabaseReference reference = firebaseDatabase.getReference("user type").child(firebaseAuth.getCurrentUser().getUid());
}
}
});
but i don't know what todo further.
Change it to
DatabaseReference reference = firebaseDatabase.getReference("usertype").child(firebaseAuth.getCurrentUser().getUid()).child("type");
i did this and it worked
firebaseAuth.signInWithEmailAndPassword(email , password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
DatabaseReference reference = firebaseDatabase.getReference("user type").child(firebaseAuth.getCurrentUser().getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String temp = snapshot.child("type").getValue().toString();
Log.d("hereIm","temp == "+temp);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
});

Null pointer exception when the widget is already initialized

I'm trying to change the user authentication email.
CustomDialogBox
public class ConfirmPasswordDialogBox extends Dialog implements android.view.View.OnClickListener {
private ImageButton cancel, confirm;
private EditText confirm_password;
public ConfirmPasswordDialogBox(#NonNull Context context) {
super(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dailog_box_foremail);
confirm_password = findViewById(R.id.password);
cancel = findViewById(R.id.cancel_btn);
confirm = findViewById(R.id.confirm_btn);
cancel.setOnClickListener(this);
confirm.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = confirm_password.getText().toString();
if(!mpassword.equals("")){
new EditProfileActivity().updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
Activity where null pointer exception is thrown
public class EditProfileActivity extends AppCompatActivity {
private EditText descript, firstName, lastName, email;
private Button updatebtn;
private ImageButton back;
private Context mcontext;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser user;
private FirebaseDatabase database;
private DatabaseReference myRef;
private FirebaseMethods firebaseMethods;
private String userID;
private ProgressDialog pb;
private UserInformation userInformationx;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mcontext = EditProfileActivity.this;
descript = findViewById(R.id.descript);
firstName = findViewById(R.id.firstName);
email = findViewById(R.id.email);
lastName = findViewById(R.id.lastName);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
firebaseMethods = new FirebaseMethods(mcontext);
pb = new ProgressDialog(this);
pb.setMessage("Updaing Profile ...");
pb.setCancelable(true);
pb.setCanceledOnTouchOutside(false);
init();
setupFirebaseAuth();
}
public void updatingemail(String password){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
.getCredential(user.getEmail(), password);
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "User re-authenticated.");
if(task.isSuccessful()){
FirebaseAuth.getInstance().fetchSignInMethodsForEmail(email.getText().toString()).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if(task.isSuccessful()){
if(task.getResult().getSignInMethods().size() == 1){
Toast.makeText(mcontext, "That email is already in use.", Toast.LENGTH_SHORT).show();
}else{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(mcontext, "Email address updated.", Toast.LENGTH_SHORT).show();
myRef.child(mcontext.getString(R.string.dbname_users))
.child(userID)
.child(mcontext.getString(R.string.email))
.setValue(email.getText().toString());
}
}
});
}
}
}
});
}
}
});
}
The EditText widget is already intialized, still email.getText.toString() is throwing null. I'm just passing the string value to a method, which is called when a button is clicked in Dialog box.
I've tried and debug all possible ways I know.
I'm just trying to update the user authentication email in firebase.
The EditText widget is already intialized, still email.getText.toString() is throwing null.
Actually the EditText email is only intialized in the onCreate of the activity, this means that it's only initialized when you open the activity using startActivity(intent).
Edit - Since you're calling the ConfirmPasswordDialogBox from the EditProfileActivity, something along the following lines should work.
public class ConfirmPasswordDialogBox extends Dialog {
private ImageButton cancel, confirm;
public EditText confirm_password;
public ConfirmPasswordDialogBox(#NonNull Context context) {
super(context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dailog_box_foremail);
confirm_password = findViewById(R.id.password);
cancel = findViewById(R.id.cancel_btn);
confirm = findViewById(R.id.confirm_btn);
//cancel.setOnClickListener(this);
//confirm.setOnClickListener(this);
}
public void setOnClickListeners(View.OnClickListener listener) {
cancel.setOnClickListener(listener);
confirm.setOnClickListener(listener);
}
/*
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = confirm_password.getText().toString();
if(!mpassword.equals("")){
new EditProfileActivity().updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
*/
}
public class EditProfileActivity extends AppCompatActivity implements android.view.View.OnClickListener {
//Other code
//At some point in some method you'll create the dialog
//Say you create the dialog object here. Now set this activity as the onClickListener
dialog.setOnClickListeners(this);
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.cancel_btn:
dismiss();
break;
case R.id.confirm_btn:
String mpassword = dialog.confirm_password.getText().toString();
if(!mpassword.equals("")){
//Now you can directly call the method
updatingemail(mpassword);
dismiss();
}else{
Toast.makeText(getContext(), "Password can't be empty.", Toast.LENGTH_SHORT).show();
}
break;
}
}
public void updatingemail(String password){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
.getCredential(user.getEmail(), password);
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "User re-authenticated.");
if(task.isSuccessful()){
FirebaseAuth.getInstance().fetchSignInMethodsForEmail(email.getText().toString()).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
#Override
public void onComplete(#NonNull Task<SignInMethodQueryResult> task) {
if(task.isSuccessful()){
if(task.getResult().getSignInMethods().size() == 1){
Toast.makeText(mcontext, "That email is already in use.", Toast.LENGTH_SHORT).show();
}else{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.updateEmail(email.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated.");
Toast.makeText(mcontext, "Email address updated.", Toast.LENGTH_SHORT).show();
myRef.child(mcontext.getString(R.string.dbname_users))
.child(userID)
.child(mcontext.getString(R.string.email))
.setValue(email.getText().toString());
}
}
});
}
}
}
});
}
}
});
}

I get duplicate data when I click on alert dialog in adapter class of fragment

I found a issue is that when I turn back the fragment , it will show duplicate data.
I try to clear the arrayList data to solve it.
But I want to know more smart way.
Is it possible to avoid this issue for duplicate data ?
Adapter Class
myHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
CharSequence options[] = new CharSequence[]{"Accept Request", "Cancel Request"};
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0){
acceptRequest(requestList.get(i).getId(),myHolder);
}
else if (which == 1){
cancelRequest(requestList.get(i).getId(),myHolder);
}
}
});
builder.show();
}
});
}
private void cancelRequest(final String uid, final MyHolder myHolder) {
friendReqDbRef
.child(current_uid)
.child(uid)
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
friendReqDbRef
.child(uid)
.child(current_uid)
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
requestList.remove(myHolder.getAdapterPosition());
notifyItemRemoved(myHolder.getAdapterPosition());
notifyItemRangeChanged(myHolder.getAdapterPosition(), requestList.size());
}
});
}
});
}

Categories

Resources