I don't know why my dialog can not be dismissed. Actually, I see in my database, the data we take successfully gets saved in that database. Just the dialog dismiss code is not working.
This is my code:
package com.app.kfstore.EmailLoginRegister;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.app.kfstore.MainActivity;
import com.app.kfstore.OperationRetrofitApi.ApiClient;
import com.app.kfstore.OperationRetrofitApi.ApiInterface;
import com.app.kfstore.OperationRetrofitApi.Users;
import com.app.kfstore.R;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class EmailRegisterActivity extends AppCompatActivity {
private EditText name,email,password;
private Button regBtn;
public static ApiInterface apiInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_register);
//////hide status bar code//////
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//////end code for hide status bar//////
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
init();
}
private void init() {
name = (EditText) findViewById(R.id.name);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
regBtn = (Button) findViewById(R.id.button2);
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Registration();
}
});
}
private void Registration() {
String user_name = name.getText().toString().trim();
String user_email = email.getText().toString().trim();
String user_password = password.getText().toString().trim();
if(TextUtils.isEmpty(user_name)){
name.setError("Name is required!");
}
else if(TextUtils.isEmpty(user_email)){
email.setError("Email is required!");
}
else if(TextUtils.isEmpty(user_password)){
password.setError("Password is required!");
}
else {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Registering...");
dialog.setMessage("Please wait while we adding your credentials");
dialog.show();
dialog.setCanceledOnTouchOutside(false);
Call<Users> call = apiInterface.performEmailRegistration(user_name,user_email,user_password);
call.enqueue(new Callback<Users>() {
#Override
public void onResponse(Call<Users> call, Response<Users> response) {
if(response.body().getResponse().equals("ok")){
Toast.makeText(EmailRegisterActivity.this, "Your account has been created", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
else if(response.body().getResponse().equals("failed!")){
Toast.makeText(EmailRegisterActivity.this, "Something went wrong, Please try again!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
else if(response.body().getResponse().equals("already")){
Toast.makeText(EmailRegisterActivity.this, "This email is already exists, Please try another email", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
#Override
public void onFailure(Call<Users> call, Throwable t) {
}
});
}
}
//////link code for text go to login page//////
public void goToLogin(View view) {
Intent intent = new Intent(EmailRegisterActivity.this, EmailLoginActivity.class);
startActivity(intent);
Animatoo.animateSlideRight(this);
finish();
}
///////end of code//////
//////link code for back button go to main page//////
public void goToMainPage(View view) {
Intent intent = new Intent(EmailRegisterActivity.this, MainActivity.class);
startActivity(intent);
Animatoo.animateSlideRight(this);
finish();
}
//////end of code//////
}
This for easy code to see( just same code but i just cut the top and bottom code)
else {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("Registering...");
dialog.setMessage("Please wait while we adding your credentials");
dialog.show();
dialog.setCanceledOnTouchOutside(false);
Call<Users> call = apiInterface.performEmailRegistration(user_name,user_email,user_password);
call.enqueue(new Callback<Users>() {
#Override
public void onResponse(Call<Users> call, Response<Users> response) {
if(response.body().getResponse().equals("ok")){
Toast.makeText(EmailRegisterActivity.this, "Your account has been created", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
else if(response.body().getResponse().equals("failed!")){
Toast.makeText(EmailRegisterActivity.this, "Something went wrong, Please try again!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
else if(response.body().getResponse().equals("already")){
Toast.makeText(EmailRegisterActivity.this, "This email is already exists, Please try another email", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
#Override
public void onFailure(Call<Users> call, Throwable t) {
}
});
}
}
Result just run dialog without dismiss dialog:
If you have any ideas or advice, I realy apreciate it.
Thanks
Just tried your code, and it works perfectly.
Make sure you have an 'else' clause in your onResponse, and dismiss the dialog in onFailure as well
#Override
public void onResponse(Call<Users> call, Response<Users> response) {
if(response.body().getResponse().equals("ok")){}
else if(response.body().getResponse().equals("failed!")){}
else if(response.body().getResponse().equals("already")){}
else {
Toast.makeText(EmailRegisterActivity.this, "Do'h, I forgot to put and 'else' clause", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
#Override
public void onFailure(Call<Users> call, Throwable t) {
Toast.makeText(EmailRegisterActivity.this, "Do'h, Failure :(", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
Related
What actually i am doing here, When a user login to their account, Then i am checking that whatever they had verified their email address or not, If not then i am starting the EmailVerificationActivity.
From where when user click on SEND VERIFICATION EMAIL Button an Email Verification code will be sent to user's email address.
after that when user successfully verified their email address, when they click SEND VERIFICATION LINK Button again.
Instead of showing toast message
Toast.makeText(this, "Your email has been verified, Now you can login.", Toast.LENGTH_LONG).show();,
sending the Email Verification link again.
Why isEmailVerified() returning the false condition.
This is my EmailVerificationActivity
package com.socialcodia.sherewatan;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class EmailVerificationActivity extends AppCompatActivity {
private TextView tvEmailAddress;
private Button btnSendVerificationEmail, btnSignOut;
//Firebase
FirebaseAuth mAuth;
FirebaseUser mUser;
String email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_verification);
//Init
tvEmailAddress = findViewById(R.id.tvEmailAddress);
btnSendVerificationEmail = findViewById(R.id.btnSendVerificationEmail);
btnSignOut = findViewById(R.id.btnSignOut);
//Firebase Init
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
// get and set email address
email = mUser.getEmail();
tvEmailAddress.setText(email);
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOut();
}
});
btnSendVerificationEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isEmailVerified();
}
});
}
private void isEmailVerified()
{
if (mAuth.getCurrentUser()!=null)
{
boolean isEmailVerified = mAuth.getCurrentUser().isEmailVerified();
if (isEmailVerified)
{
Toast.makeText(this, "Your email has been verified, Now you can login.", Toast.LENGTH_LONG).show();
}
else
{
sendVerificationEmail();
}
}
}
private void sendVerificationEmail()
{
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(EmailVerificationActivity.this, "Email verification link has been sent", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(EmailVerificationActivity.this, "Oops! Failed to send email verification link", Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendToLoginWithEmail()
{
Intent intent= new Intent(getApplicationContext(),LoginActivity.class);
intent.putExtra("email",email);
startActivity(intent);
finish();
}
private void signOut()
{
mAuth.signOut();
sendToLoginWithEmail();
}
}
You need to reload current user information. You see the data of the user your have from authentication are old and you need to retrieve the latest. Use the reload() method for that.
How i solved the error.
private void isEmailVerified()
{
mAuth.getCurrentUser().reload().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
if (mAuth.getCurrentUser()!=null)
{
boolean isEmailVerified = mAuth.getCurrentUser().isEmailVerified();
if (isEmailVerified)
{
Toast.makeText(getApplicationContext(), "Your email has been verified, Now you can login.", Toast.LENGTH_LONG).show();
}
else
{
sendVerificationEmail();
}
}
}
});
}
I used the following line to solve this problem
await FirebaseAuth.instance.currentUser!.reload();
My app uses firebase and it needs to send a verification email to the user after registration before they can login. In my code, the app fails to send the verification email and I found out that the user is always null (while debugging) in line 86/88 of my code. any help would be greaty appreciated.
I've tried retracing my steps back but I couldn't get where i nicked an artery
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import static android.text.TextUtils.isEmpty;
public class LoginActivity extends AppCompatActivity {
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuthSetUp();
//widgets
TextView mSignUp = (TextView) findViewById(R.id.sign_up_txt);
TextView forgotPassword = (TextView) findViewById(R.id.forgot_password_txt);
Button mSignIn = (Button) findViewById(R.id.sign_in_btn);
final EditText mEmailSignIn = (EditText) findViewById(R.id.sign_in_email);
final EditText mPasswordSignIn = (EditText) findViewById(R.id.sign_in_password);
mSignUp.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(intent);
}
}));
//sign in process
mSignIn.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isEmpty(mEmailSignIn.getText().toString()) && !isEmpty(mPasswordSignIn.getText().toString())) {
//showProgressBar();
FirebaseAuth.getInstance().signInWithEmailAndPassword(mEmailSignIn.getText().toString(), mPasswordSignIn.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//hideProgressBar();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, " Authentication Failed!!!", Toast.LENGTH_LONG).show();
//hideProgressBar();
}
});
} else {
Toast.makeText(LoginActivity.this, "Please, Fill All Fields", Toast.LENGTH_LONG).show();
}
}
}));
}
//Setting up Firebase
private void firebaseAuthSetUp() {
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
Log.d("TAG", "CurrentUser: " + user);
if (user != null) {
if(user.isEmailVerified()){
Log.d("TAG", "onAuthStateChanged: signed in: " + user.getEmail());
Toast.makeText(LoginActivity.this, "signed in " + user.getUid(), Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginActivity.this, "Please Check Your Email Inbox for Verification Link " + user.getUid(), Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
}
} else {
Toast.makeText(LoginActivity.this, "failed to sign in", Toast.LENGTH_LONG).show();
}
}
};
}
#Override
protected void onStart() {
super.onStart();
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if (mAuthListener != null) {
FirebaseAuth.getInstance().addAuthStateListener(mAuthListener);
}
}
/*public void showProgressBar(){
mProgressBar.setVisibility(View.VISIBLE);
}
public void hideProgressBar(){
if (mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.INVISIBLE);
}
}*/
}```
Thanks a lot #Praveen and #Alex... figured it out, I made a mistake of signing out the user in the else statement [of the if(user.isEmailVerified()) block in the firebaseAuthSetup() method]. probably wouldn't have gotten it if I didn't retrace from the onComplete()
When I log in through facebook, I am supposed to get some data from Facebook such as my email, name and profile picture. However, now I can't get the data anymore after I added these codes
#Override
public void onSuccess(LoginResult loginResult) {
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Toast.makeText(getApplicationContext(), "Login Success with Facebook", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
I am supposed to get these Facebook datas in this activity
package com.example.musix.Musix;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.musix.MainActivity;
import com.example.musix.R;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.google.firebase.auth.FirebaseAuth;
import org.json.JSONException;
import org.json.JSONObject;
public class ViewProfile extends AppCompatActivity {
private ImageView circleImageView;
private TextView txtName,txtEmail;
private ImageButton Home;
private ImageButton Playlist;
private FirebaseAuth firebaseAuth;
private Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_profile);
circleImageView = (ImageView) findViewById(R.id.profile_icon);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
Home = (ImageButton)findViewById(R.id.home);
Playlist = (ImageButton)findViewById(R.id.playlisticon);
firebaseAuth = FirebaseAuth.getInstance();
logout = (Button)findViewById(R.id.btnLogout);
//go to LoginScreen page
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
startActivity(new Intent(ViewProfile.this, LoginScreen.class));
}
});
//go to Playlist page
Playlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ViewProfile.this, Playlist.class));
}
});
//go to MainActivity page
Home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ViewProfile.this, MainActivity.class));
}
});
checkLoginStatus();
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null){
txtName.setText("");
txtEmail.setText("");
circleImageView.setImageResource(0);
}
else{
loaduserProfile(currentAccessToken);
}
}
};
//get Facebook profile data
private void loaduserProfile(AccessToken newAccessToken){
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+id+ "/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(ViewProfile.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name, last_name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
//display Facebook profile data if already logged in
private void checkLoginStatus(){
if(AccessToken.getCurrentAccessToken()!= null){
loaduserProfile(AccessToken.getCurrentAccessToken());
}
}
}
My facebook login page
package com.example.musix.Musix;
import android.app.ProgressDialog;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.musix.MainActivity;
import com.example.musix.R;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphRequestAsyncTask;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
public class LoginScreen extends AppCompatActivity {
private EditText Username;
private EditText Password;
private Button Login;
private LoginButton FacebookLogin;
private ImageView circleImageView;
private TextView txtName,txtEmail;
private TextView userRegistration;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private TextView forgotPassword;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
Username = (EditText) findViewById(R.id.etName);
Password = (EditText) findViewById(R.id.etPassword);
Login = (Button) findViewById(R.id.btnLogin);
FacebookLogin = (LoginButton) findViewById(R.id.facebookLogin);
txtName = findViewById(R.id.profile_name);
txtEmail = findViewById(R.id.profile_email);
circleImageView = (ImageView) findViewById(R.id.profile_icon);
userRegistration = (TextView)findViewById(R.id.tvRegister);
forgotPassword = (TextView)findViewById(R.id.tvForgotPassword);
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
finish();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((Username.length() > 0) && (Password.length() > 0)) ||(AccessToken.getCurrentAccessToken()!= null)){
validate(Username.getText().toString(), Password.getText().toString());
}
else if((Username.length() == 0) && (Password.length() > 0)){
Username.setError("Enter Username");
}
else if((Password.length() == 0) && (Username.length() > 0)){
Password.setError("Enter Password");
}
else{
Username.setError("Enter Username");
Password.setError("Enter Password");
}
}
});
userRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginScreen.this, SignUp.class));
}
});
callbackManager = CallbackManager.Factory.create();
FacebookLogin.setReadPermissions(Arrays.asList("email", "public_profile"));
checkLoginStatus();
FacebookLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
final AccessToken accessToken = loginResult.getAccessToken();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Toast.makeText(getApplicationContext(), "Login Success with Facebook", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Login Failed", Toast.LENGTH_SHORT).show();
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginScreen.this, ForgotPassword.class));
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if(currentAccessToken == null){
txtName.setText("");
txtEmail.setText("");
circleImageView.setImageResource(0);
}
else{
loaduserProfile(currentAccessToken);
}
}
};
//get Facebook profile data
private void loaduserProfile(AccessToken newAccessToken){
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+id+ "/picture?type=normal";
txtEmail.setText(email);
txtName.setText(first_name +" "+last_name);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
Glide.with(LoginScreen.this).load(image_url).into(circleImageView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name, last_name, email, id");
request.setParameters(parameters);
request.executeAsync();
}
//display Facebook profile data if already logged in
private void checkLoginStatus(){
if(AccessToken.getCurrentAccessToken()!= null){
loaduserProfile(AccessToken.getCurrentAccessToken());
}
}
private void validate(String userUsername, String userPassword){
//show login progress
progressDialog.setMessage("Loading . . .");
progressDialog.show();
//Login admin account
if((userUsername.equals("Admin")) && (userPassword.equals("12345"))){
Intent intent = new Intent(LoginScreen.this, MainActivity.class);
startActivity(intent);
finish();
}
//Login using firebase-registered accounts
else{
firebaseAuth.signInWithEmailAndPassword(userUsername,userPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isComplete()){
progressDialog.dismiss();
Toast.makeText(LoginScreen.this, "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginScreen.this, MainActivity.class));
}
else{
progressDialog.dismiss();
Toast.makeText(LoginScreen.this, "The username or password you entered is incorrect.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
#Override
public void onCompleted(JSONObject user, GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
Here you are logging yourself out the moment you are succesfully logged in. Remove
LoginManager.getInstance().logOut();
I am trying to create a registration Activity in my android application when I compile it runs without and error it seems like there is a logical problem when I run my application instant of creating a new account it jumps to the error code as I have provided my registration activity code in the in method creatnewAccount() in the if statement where I have tried to check whether the rpassword and the password are same. Whenever I run my application and enter the detail and click signup button it jumps to the else statement. Can't understand what's the error and what should I do
package com.nanb.chaton;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import static android.widget.Toast.LENGTH_SHORT;
public class Register extends AppCompatActivity {
private EditText Email, Password, Repassword;
private Button Signup, Login;
private FirebaseAuth mAuth;
private ProgressDialog lodingBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth = FirebaseAuth.getInstance();
rimplemantaion();
sendusertoLogin();
createAccount();
}
private void createAccount() {
Signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createnewAccount();
}
});
}
private void createnewAccount() {
String email = Email.getText().toString();
String password = Password.getText().toString();
String rpassword = Repassword.getText().toString();
if (TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter email i'd ", LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter Password ", LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(rpassword)){
Toast.makeText(this, "Please enter Re-Password ", LENGTH_SHORT).show();
}
if (rpassword == password ){
lodingBar.setTitle("Creating new account");
lodingBar.setMessage("Pleased wait till we creat your account");
lodingBar.setCanceledOnTouchOutside(true);
lodingBar.show();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
sendusertoLogin();
Toast.makeText(Register.this,"Account created succcessfully", Toast.LENGTH_SHORT).show();
lodingBar.dismiss();
}else{
Toast.makeText(Register.this,"Sorry,There is a problem while creating your accout. Please try again later", LENGTH_SHORT).show();
lodingBar.dismiss();
}
}
});
}
else{
Toast.makeText(this, "Password and Re-enter password are not same ", LENGTH_SHORT).show();
}
}
private void sendusertoLogin() {
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginIntent = new Intent(Register.this, Login.class);
startActivity(loginIntent);
}
});
}
private void rimplemantaion() {
Email = (EditText) findViewById(R.id.email);
Password = (EditText) findViewById(R.id.password);
Repassword = (EditText) findViewById(R.id.Rpassword);
Signup = (Button) findViewById(R.id.SignUp);
Login = (Button) findViewById(R.id.LogIn);
lodingBar = new ProgressDialog(this);
}
}
Replace this
if (rpassword == password ){
}
else{
Toast.makeText(this, "Password and Re-enter password are not same ", LENGTH_SHORT).show();
}
with this
if (rpassword.equals(password) ){
}
else{
Toast.makeText(this, "Password and Re-enter password are not same ", LENGTH_SHORT).show();
}
I have an issue regarding signing in..!
package com.example.myapplication;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
public class RegisterActivity extends AppCompatActivity
{
private Button CreateAccountButton;
private EditText InputName, InputPhoneNumber, InputPassword;
private ProgressDialog loadingBar;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
CreateAccountButton = (Button) findViewById(R.id.main_register_btn);
InputName = (EditText) findViewById(R.id.register_username_input);
InputPassword = (EditText) findViewById(R.id.register_password_input);
InputPhoneNumber = (EditText) findViewById(R.id.register_phone_number_input);
loadingBar = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
CreateAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
CreateAccount();
}
});
}
private void CreateAccount()
{
String name = InputName.getText().toString();
String phone = InputPhoneNumber.getText().toString();
String password = InputPassword.getText().toString();
if (TextUtils.isEmpty(name))
{
Toast.makeText(this, "please enter your name", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(phone))
{
Toast.makeText(this, "please enter your phone number", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "please enter your password", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Create Account");
loadingBar.setMessage("Please wait, While we are checking the credentials");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
validatephonenumber(name, phone, password);
}
}
private void validatephonenumber(final String name, final String phone, final String password)
{
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if(dataSnapshot.child("Users").child(phone).exists())
{ Toast.makeText(RegisterActivity.this, "this" +phone+ "alredy exists", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Toast.makeText(RegisterActivity.this, "Please try using another phone number", Toast.LENGTH_SHORT).show();
Intent intent= new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
}
else
{
HashMap<String, Object> userdataMap = new HashMap<>();
userdataMap.put("Phone", phone);
userdataMap.put("password", password);
userdataMap.put("name", name);
RootRef.child("User").child(phone).updateChildren(userdataMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(RegisterActivity.this, "Congratulations your account has been created ", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent= new Intent(RegisterActivity.this, loginActivity.class);
startActivity(intent);
}
else
{
loadingBar.dismiss();
Toast.makeText(RegisterActivity.this, "Network Error: Please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
when I'm using this code and signing in with a phone number for the second it should actually prompt "this number already exists" but it isn't working and upon signing in with the same number again all the older names and passwords are being replaced by new ones....how can I solve this issue???
try to remove your intent flow ;-
Intent intent= new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);