I would like to show an error message within an alert dialog box for password reset, however no error message shows inside the dialog pop up.
Alert Dialog Box
When clicking "Reset" the dialog box will close. However, entering in a valid email does show the toast message "Reset Email Sent"
The validations are 1) leaving the email address empty , 2)not giving a proper email
Login.java
//onclick for forgot password
forgotPText = findViewById(R.id.forgotPassText);
forgotPText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start alert dialog
View view = inflater.inflate(R.layout.reset_popup,null);
reset_alert.setTitle("Forgot Password ?")
.setMessage("Enter Email For Password Reset Link.")
.setPositiveButton("Reset", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//validate the email address is not empty or not valid email
EditText email = view.findViewById(R.id.reset_popup_Email);
String emailChar = email.getText().toString();
if (email.getText().toString().isEmpty()){
email.setError("Required Field!");
return;
}
if(!Patterns.EMAIL_ADDRESS.matcher(emailChar).matches()){
email.setError("Please provide valid email!");
email.requestFocus();
return;
}
//send reset link
firebaseAuth.sendPasswordResetEmail(email.getText().toString())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//FirebaseUser user = firebaseAuth.getCurrentUser();
//updateUI(user);
Toast.makeText(LoginActivity.this
, "Reset Email Sent", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}).setNegativeButton("Cancel",null)
.setView(view)
.create().show();
}
});
Use this code:
forgotPText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start alert dialog
LayoutInflater inflater = getLayoutInflater();
AlertDialog.Builder reset_alert = new AlertDialog.Builder(MainActivity.this);
View view = inflater.inflate(R.layout.reset_popup,null);
reset_alert.setView(view);
EditText email = view.findViewById(R.id.email);
TextView tv_cancel = view.findViewById(R.id.tv_cancel);
TextView tv_submit = view.findViewById(R.id.tv_submit);
tv_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
new Handler().postDelayed(new Runnable() {
#Override
public void run() { alertDialog.dismiss(); }}, 200);
}
});
email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
});
tv_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
String emailChar = email.getText().toString();
if (email.getText().toString().isEmpty()){
email.setError("Required Field!");
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(emailChar).matches()){
email.setError("Please provide valid email!");
email.requestFocus();
return;
}
//send reset link
firebaseAuth.sendPasswordResetEmail(email.getText().toString())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//FirebaseUser user = firebaseAuth.getCurrentUser();
//updateUI(user);
Toast.makeText(LoginActivity.this
, "Reset Email Sent", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
});
alertDialog = reset_alert.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
});
//////// reset_popup.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/reset_alert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Forgot Password?"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/des"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:textColor="#color/black"
android:text="Enter Email For Password Reset Link."
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/reset_alert" />
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:hint="Email Address"
android:inputType="textEmailAddress"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/des" />
<TextView
android:id="#+id/tv_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Cancel"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/tv_submit"
app:layout_constraintTop_toBottomOf="#+id/email" />
<TextView
android:id="#+id/tv_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:layout_marginEnd="353dp"
android:text="Reset"
android:textColor="#color/black"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/email" />
</androidx.constraintlayout.widget.ConstraintLayout>
Related
So I am developing one android application in which I have created one custom dialog box. but the problem arises that, this dialog box is showing correct in my phone and on emulator also. But it can't get display properly on redmi or other phones.
Here is screenshot on my mobile device
and [![On other device][2]][2]
On other device
[2]: https://i.stack.imgur.com/b3H4J.jpg
Here is my code:-
custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFF538"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Would you like to continue"
android:textColor="#color/black"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/bld"
android:layout_width="269dp"
android:layout_height="wrap_content"
android:textColor="#color/black" />
<EditText
android:id="#+id/txt_input"
android:layout_width="382dp"
android:layout_height="69dp"
android:layout_marginTop="10dp"
android:background="#drawable/back"
android:hint="Why are you sending this request?"
android:maxLength="100"
android:textSize="20sp" />
<!-- In given textview we have used maxlength =100
because we have to display small information so we use limited characters.-->
<TextView
android:layout_width="wrap_content"
android:layout_height="117dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="11dp"
android:text="Your request will display publicly in blood request section.And if your any request is present in Blood Request will be deleted"
android:textColor="#FF0303"
android:textSize="20dp" />
<Button
android:id="#+id/btn_okay"
android:layout_width="134dp"
android:layout_height="60dp"
android:layout_weight="0"
android:layout_marginTop="10dp"
android:backgroundTint="#color/black"
android:text="yes"
android:textColor="#ffffff"
android:textSize="18sp" />
<Button
android:id="#+id/btn_cancel"
android:layout_width="136dp"
android:layout_height="60dp"
android:layout_gravity="right"
android:layout_marginTop="-58dp"
android:layout_weight="0"
android:backgroundTint="#color/black"
android:gravity="center"
android:text="no"
android:textColor="#ffffff"
android:textSize="18sp" />
</LinearLayout>
donor.java
private void alertDialog() {
final AlertDialog.Builder alert = new AlertDialog.Builder(Bloodbank.this);
View mView = getLayoutInflater().inflate(R.layout.custom_dialog2, null);
Button btn_cancel = (Button) mView.findViewById(R.id.btn_cancel);
Button btn_okay = (Button) mView.findViewById(R.id.btn_okay);
TextView bld = (TextView) mView.findViewById(R.id.bld);
bld.setText("selected blood group is "+item);
alert.setView(mView);
final AlertDialog alertDialog = alert.create();
alertDialog.setCanceledOnTouchOutside(false);
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Request dismissed", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
btn_okay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
SQLiteDatabase db = dbHandler.getWritableDatabase();
String sql1 = "delete from request where time < date('now','-2 day') AND Username = '" + MainActivity.getValue() + "'";
db.execSQL(sql1);
String sql = "select Name,contactNo from request where Username = '" + MainActivity.getValue() + "'";
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
runOnUiThread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE));
Toast.makeText(getApplicationContext(), "your request is pending. Please delete that first.", Toast.LENGTH_SHORT).show();
}
});
}
});
}
while (cursor.moveToNext());
}
catch (Exception e) {
runOnUiThread(new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
Toast.makeText(getApplicationContext(), "Please select blood group first", Toast.LENGTH_SHORT).show();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
alertDialog.dismiss();
}
});
alertDialog.show();
alertDialog.getWindow().setLayout(700, 833); //Controlling width and height.
}
Try to change these lines
alertDialog.show();
alertDialog.getWindow().setLayout(700, 833); //Controlling width and height.
With these line
int width = (int) (getResources().getDisplayMetrics().widthPixels * 0.90);
int height = (int) (getResources().getDisplayMetrics().heightPixels * 0.60);
if (alertDialog.getWindow() != null) {
alertDialog.getWindow().setLayout(width, height);
}
alertDialog.show();
I have the following method where I am trying to inflate layout in altert dialog but nothing happen. I am building todo app and i want to show dialog when i click on add image button.
I need your help to fix that problem.
Any help would be greatly appreciated :)
imageButton.setOnClickListener(v -> {
Toast.makeText(MainActivity.this, "Button add clicked ", Toast.LENGTH_SHORT).show();
LayoutInflater inflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewInput = inflater.inflate(R.layout.note_input,null,false);
EditText editTitle = viewInput.findViewById(R.id.edit_text);
EditText editDescription = viewInput.findViewById(R.id.edit_description);
new AlertDialog.Builder(MainActivity.this)
.setView(viewInput)
.setTitle("Add Note")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String title = editTitle.getText().toString();
String description = editDescription.getText().toString();
Note note = new Note(title,description);
boolean isInserted = new NoteHandler(MainActivity.this).create(note);
if(isInserted){
Toast.makeText(MainActivity.this, "Note saved", Toast.LENGTH_SHORT).show();
loadNotes();
}
else{
Toast.makeText(MainActivity.this, "Unable to save the note", Toast.LENGTH_SHORT).show();
}
dialog.cancel();
}
});
});
XML FILE
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Note title"
app:layout_constraintBottom_toTopOf="#+id/edit_description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/edit_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:hint="Note description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
new AlertDialog.Builder(MainActivity.this)
.setView(viewInput)
.setTitle("Add Note")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String title = editTitle.getText().toString();
String description = editDescription.getText().toString();
Note note = new Note(title,description);
boolean isInserted = new NoteHandler(MainActivity.this).create(note);
if(isInserted){
Toast.makeText(MainActivity.this, "Note saved", Toast.LENGTH_SHORT).show();
loadNotes();
}
else{
Toast.makeText(MainActivity.this, "Unable to save the note", Toast.LENGTH_SHORT).show();
}
dialog.cancel();
}
}).show();//Need to ad .show() right here
I'm new to android studio. Currently I'm working on a medlabtut app on android for over 3 months now. I'm having an issue on the login button on the MedLabStartUpScreen that actually supposed to launch the login screen when clicked on. Rather it crashes the app completely and shows a runtimeException at my //Connection Hooks "progressbar = findViewById(R.id.login_progress_bar);" of my login.java class file, that android.widget.ProgressBar cannot be cast to android.widget.RelativeLayout. I need your help please
My Login layout activity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Common.LoginSignup.Login"
android:orientation="vertical"
android:background="#fff"
android:padding="25dp"
android:transitionName="transition_login">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/logo_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Welcome Back! Login Here"
android:textSize="40sp"
android:transitionName="logo_text"
android:fontFamily="#font/bungee"
android:textColor="#000"
android:layout_marginTop="20dp"/>
<TextView
android:id="#+id/slogan_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign In to continue"
android:textSize="18sp"
android:layout_marginTop="10dp"
android:fontFamily="#font/muli_black"
android:transitionName="logo_desc"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_marginBottom="20dp">
<com.hbb20.CountryCodePicker
android:id="#+id/login_country_code_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:ccp_autoDetectCountry="true"
app:ccp_showFlag="true"
app:ccp_showNameCode="true"
app:ccp_showFullName="true"
android:padding="5dp"
android:background="#drawable/black_border"/>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_below="#+id/login_country_code_picker"
android:id="#+id/login_phone_number"
android:layout_height="wrap_content"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:hint="#string/phone_number"
android:textColorHint="#color/Black"
app:boxStrokeColor="#color/Black"
app:boxStrokeWidthFocused="2dp"
app:endIconMode="clear_text"
app:endIconTint="#color/Black"
app:hintTextColor="#color/Black"
app:startIconDrawable="#drawable/field_phone_number_icon"
app:startIconTint="#color/Black">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/login_phone_number_editText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="phone" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/login_password"
android:layout_below="#+id/login_phone_number"
android:hint="#string/password"
app:startIconDrawable="#drawable/field_password_icon"
app:startIconTint="#color/Black"
android:transitionName="password_tran"
app:passwordToggleEnabled="true"
app:passwordToggleTint="#color/Black"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/login_password_editText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="#font/muli_bold"
android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>
<RelativeLayout
android:id="#+id/forget_password_block"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_password"
android:layout_marginTop="10dp">
<CheckBox
android:id="#+id/remember_me"
style="#style/Widget.AppCompat.CompoundButton.CheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="#string/remember_me" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/forget_password"
android:background="#00000000"
android:layout_alignParentEnd="true"
android:onClick="callForgetPassword"
android:layout_alignParentRight="true"/>
</RelativeLayout>
<Button
android:id="#+id/letTheUserLogin"
android:layout_below="#+id/forget_password_block"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:background="#000"
android:text="#string/login"
android:onClick="letTheUserLoggedIn"
android:textColor="#fff"
android:transitionName="button_tran" />
<RelativeLayout
android:id="#+id/login_sign_google_box"
android:layout_width="match_parent"
android:layout_height="50dp"
android:padding="10dp"
android:layout_margin="5dp"
android:background="#drawable/rounded_rectangle"
android:layout_below="#+id/letTheUserLogin">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/signin_with_google_icon"
android:layout_centerVertical="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SIGN IN WITH GOOGLE"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:fontFamily="#font/muli_bold"
android:layout_margin="5dp"
android:textColor="#000"/>
<Button
android:id="#+id/google_signIn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/transparent" />
</RelativeLayout>
<Button
android:id="#+id/signup_screen"
android:layout_below="#+id/login_sign_google_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:text="Create Account"
android:layout_centerHorizontal="true"
android:elevation="0dp"
android:layout_margin="5dp"
android:textColor="#000"
android:transitionName="login_signup_tran"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:layout_centerInParent="true"
android:background="#drawable/white_circle"
android:elevation="10dp">
<ProgressBar
android:id="#+id/login_progress_bar"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
<ImageView
android:id="#+id/social_fb"
android:layout_below="#+id/signup_screen"
android:layout_width="50dp"
android:layout_height="45dp"
android:src="#drawable/social_facebook_icon"
android:layout_marginLeft="130dp" />
<ImageView
android:id="#+id/social_tw"
android:layout_below="#id/signup_screen"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_centerHorizontal="true"
android:layout_marginLeft="150dp"
android:src="#drawable/social_twitter_icon" />
<ImageView
android:id="#+id/social_wh"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_below="#id/signup_screen"
android:layout_marginLeft="250dp"
android:src="#drawable/social_whatsapp_icon" />
</RelativeLayout>
</LinearLayout>
And the code for login.java class file
public class Login extends AppCompatActivity {
CountryCodePicker countryCodePicker;
Button callSignUp, login_btn;
TextView logoText, sloganText;
TextInputLayout username, phoneNumber, password;
RelativeLayout progressbar;
CheckBox rememberMe;
EditText phoneNumberEditText, passwordEditText;
private GoogleSignInClient mGoogleSignInClient;
private final static int RC_SIGN_IN = 123; // request code
Button verify;
private FirebaseAuth mAuth;
#Override
protected void onStart() {
super.onStart();
FirebaseUser user = mAuth.getCurrentUser();
if (user!=null){
Intent intent = new Intent(getApplicationContext(), MedLabDashboard.class);
startActivity(intent);
}
}
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
createRequest();
//when the user clicks the google button,call the signIn method
findViewById(R.id.google_signIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
//Connection Hooks
countryCodePicker = findViewById(R.id.country_code_picker);
phoneNumber = findViewById(R.id.login_phone_number);
progressbar = findViewById(R.id.login_progress_bar);
callSignUp = findViewById(R.id.signup_screen);
image = findViewById(R.id.logo_image);
logoText = findViewById(R.id.logo_name);
sloganText = findViewById(R.id.slogan_name);
password = findViewById(R.id.login_password);
login_btn = findViewById(R.id.Login_btn);
rememberMe = findViewById(R.id.remember_me);
phoneNumberEditText = findViewById(R.id.login_phone_number_editText);
passwordEditText = findViewById(R.id.login_password_editText);
//Check whether phone number and password is already saved in Shared Preference or not
SessionManager sessionManager = new SessionManager(Login.this, SessionManager.SESSION_REMEMBERME);
if (sessionManager.checkRemeberMe()){
HashMap<String,String> rememberMeDetails = sessionManager.getRememberMeDetailFromSession();
phoneNumberEditText.setText(rememberMeDetails.get(SessionManager.KEY_SESSIONPHONENUMBER));
passwordEditText.setText(rememberMeDetails.get(SessionManager.KEY_SESSIONPASSWORD));
}
callSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Login.this, SignUp.class);
Pair[] pairs = new Pair[7];
pairs[0] = new Pair<View, String>(image, "logo_image");
pairs[1] = new Pair<View, String>(logoText, "logo_name");
pairs[2] = new Pair<View, String>(sloganText, "logo_desc");
pairs[3] = new Pair<View, String>(username, "username_tran");
pairs[4] = new Pair<View, String>(password, "password_tran");
pairs[5] = new Pair<View, String>(login_btn, "button_tran");
pairs[6] = new Pair<View, String>(callSignUp, "login_signup_tran");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
try {
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
//Setting Auto Google Sign In request
private void createRequest() {
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
//SignIn with google method that'll pop-up user google accounts (Intent)
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
//Google Sign in was successful, authenticate with firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e){
//Sign in failed, update UI appropriately
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = mAuth.getCurrentUser();
Intent intent = new Intent(getApplicationContext(), MedLabDashboard.class);
startActivity(intent);
} else {
Toast.makeText(Login.this, "Sorry authentication failed", Toast.LENGTH_SHORT).show();
}
}
});
}
//login the user in app
public void letTheUserLoggedIn(View view) {
//Check the internet connection
CheckInternet checkInternet = new CheckInternet();
if (!isConnected(Login.this)) {
showCustomDialog();
}
//validate user and password
if (!validateFields()) {
return;
}
progressbar.setVisibility(View.VISIBLE);
//get value from fields
String _phoneNumber = phoneNumber.getEditText().getText().toString().trim();
final String _password = password.getEditText().getText().toString().trim();
if (_phoneNumber.charAt(0) == '0') { //if the user uses proceeding zero (0)
_phoneNumber = _phoneNumber.substring(1);
}
final String _completePhoneNumber = "+" + countryCodePicker.getFullNumber() + _phoneNumber;
//Remember me checkbox
if (rememberMe.isChecked()){
SessionManager sessionManager = new SessionManager(Login.this,SessionManager.SESSION_REMEMBERME);
sessionManager.createRememberMeSession(_phoneNumber, _password);
}
//database query if user exist or not
Query checkUser = FirebaseDatabase.getInstance().getReference("Users").orderByChild("phoneNo").equalTo(_completePhoneNumber);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) { //if the data has arrived or exists
phoneNumber.setError(null); //if there's any error on the phoneNumber, remove
phoneNumber.setErrorEnabled(false); //if there is error space, set to false
String systemPassword = dataSnapshot.child(_completePhoneNumber).child("password").getValue(String.class);
//if password exist and matches with users password, then get other fields from firebase database
if (systemPassword.equals(_password)) {
password.setError(null); //if there's any error on the password, remove
password.setErrorEnabled(false); //if there is error space, set to false
String _fullname = dataSnapshot.child(_completePhoneNumber).child("fullName").getValue(String.class);
String _username = dataSnapshot.child(_completePhoneNumber).child("username").getValue(String.class);
String _email = dataSnapshot.child(_completePhoneNumber).child("email").getValue(String.class);
String _phoneNo = dataSnapshot.child(_completePhoneNumber).child("phoneNo").getValue(String.class);
String _password = dataSnapshot.child(_completePhoneNumber).child("password").getValue(String.class);
String _dateOfBirth = dataSnapshot.child(_completePhoneNumber).child("date").getValue(String.class);
String _gender = dataSnapshot.child(_completePhoneNumber).child("gender").getValue(String.class);
//Create a session
SessionManager sessionManager = new SessionManager(Login.this, SessionManager.SESSION_USERSESSION);
sessionManager.createLoginSession(_fullname, _username, _email, _phoneNo, _password, _dateOfBirth, _gender);
startActivity(new Intent(getApplicationContext(), MedLabDashboard.class));
Toast.makeText(Login.this, _fullname + "\n" + _email + "\n" + _phoneNo + "\n" + _dateOfBirth, Toast.LENGTH_SHORT).show();
progressbar.setVisibility(View.GONE);
} else {
progressbar.setVisibility(View.GONE);
Toast.makeText(Login.this, "Password does not match!", Toast.LENGTH_SHORT).show();
}
} else {
progressbar.setVisibility(View.GONE);
Toast.makeText(Login.this, "No such user exist", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
progressbar.setVisibility(View.GONE);
Toast.makeText(Login.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
//check internet connection
private boolean isConnected(Login login) {
ConnectivityManager connectivityManager = (ConnectivityManager) login.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiConn = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileConn = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ((wifiConn != null && wifiConn.isConnected()) || (mobileConn != null && mobileConn.isConnected())) {
return true;
} else {
return false;
}
}
private void showCustomDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
builder.setMessage("Please connect to the internet to continue");
builder.setCancelable(false)
.setPositiveButton("Connect", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(getApplicationContext(), MedLabStartUpScreen.class));
finish();
}
});
}
private boolean validateFields() {
String _phoneNumber = phoneNumber.getEditText().getText().toString().trim();
String _password = password.getEditText().getText().toString().trim();
if (_phoneNumber.isEmpty()) {
phoneNumber.setError("Phone number cannot be empty");
phoneNumber.requestFocus();
return false;
} else if (_password.isEmpty()) {
password.setError("Password cannot be empty");
password.requestFocus();
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
public void callForgetPassword(View view){
startActivity(new Intent(getApplicationContext(), ForgetPassword.class));
}
#Override
public void onBackPressed() {
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
finish();
}}
MedLabStartUpScreen Activity screen
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/White"
android:padding="30dp"
tools:context=".Common.LoginSignup.MedLabStartUpScreen">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="300dp"
android:src="#drawable/splash_screen" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="120dp"
android:fontFamily="#font/muli_black"
android:text="#string/medlab_heading"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#color/Black"
android:textSize="36sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:fontFamily="#font/muli_light"
android:text="#string/medlab_tab_line"
android:textAlignment="center"
android:textColor="#color/Black" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp">
<Button
android:id="#+id/login_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:onClick="callLoginScreen"
android:layout_weight="1"
android:background="#color/colorPrimaryDark"
android:text="#string/login"
android:textColor="#color/Black"
tools:ignore="ButtonStyle"
android:transitionName="transition_login"/>
<Button
android:id="#+id/signup_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:background="#color/colorPrimaryDark"
android:text="#string/sign_up"
android:textColor="#color/Black" />
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="#string/how_we_work"
android:textColor="#color/Black"
android:layout_marginTop="20dp"
android:background="#00000000"/>
</LinearLayout>
</ScrollView>
MedLabStartUPScreen.java class that has the login button
public class MedLabStartUpScreen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_med_lab_start_up_screen);
}
public void callLoginScreen(View view){
Intent intent = new Intent(getApplicationContext(), Login.class);
Pair[] pairs = new Pair[1];
pairs[0] = new Pair<View,String>(findViewById(R.id.login_btn), "transition_login");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MedLabStartUpScreen.this, pairs);
startActivity(intent, options.toBundle());
}
else {
startActivity(intent);
}
}
}
On around line 7 you declare this variable:
RelativeLayout progressbar;
You then correctly go on to initialise this variable with:
progressbar = findViewById(R.id.login_progress_bar);
The issue is that in the xml, the view (widget) with this ID is a ProgressBar, but the type declaration for progressbar in the Java code is RelativeLayout. Your code is therefore trying to cast the ProgressBar in the layout file into a RelativeLayout, which can't be done.
You can fix this by changing the declaration on line 7 to:
ProgressBar progressbar;
(And then adding the necessary import at the top of your Java file: import android.widget.ProgressBar;).
Hope this helped.
I would Like to save my checkbox always checked after the first checking, when the user presses it , the thing works but when i exit the app the check box is reseted , is there a way to prevent this? Now I have to check it again every time I move out the page login:
I want also to Log in only one time sow I dont have to repeat it each time I go out the application or when I come back to the login page
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
EditText mEmail,mPassword;
TextView mCreateBtn,forgotTextLink;
Button mLoginBtn;
ProgressBar progressBar;
FirebaseAuth fAuth;
CheckBox Remember;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
BottomNavigationView bandeauNavigationView = findViewById(R.id.bandeau_navigation);
bandeauNavigationView.setSelectedItemId(R.id.accueil);
bandeauNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.accueil:
return true;
case R.id.commerce:
startActivity(new Intent(getApplicationContext(),PageCommercial.class));
overridePendingTransition(0,0);
return true;
case R.id.services:
startActivity(new Intent(getApplicationContext(),Support.class));
overridePendingTransition(0,0);
return true;
case R.id.info:
startActivity(new Intent(getApplicationContext(),Info.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
mEmail = findViewById(R.id.email);
mPassword = findViewById(R.id.password1);
progressBar = findViewById(R.id.progressBar1);
fAuth = FirebaseAuth.getInstance();
mLoginBtn = findViewById(R.id.loginBtn1);
mCreateBtn = findViewById(R.id.createText1);
forgotTextLink = findViewById(R.id.forgotPassword);
Remember=findViewById(R.id.remember_me);
////////////////////////////////////
Remember.isChecked();
sharedPreferences=getSharedPreferences("LoginPrefs", MODE_PRIVATE);
editor=sharedPreferences.edit();
/////////////////To get Stored Data/////////////////////////////////
progressBar.setVisibility(View.GONE);
String email=sharedPreferences.getString("email","");
String passwords=sharedPreferences.getString("mot de passe","");
mEmail.setText(email);
mPassword.setText(passwords);
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
mEmail.setError("Email manquant.");
return;
}
if(TextUtils.isEmpty(password)){
mPassword.setError("Mot de passe manquant.");
return;
}
if(password.length() < 8){
mPassword.setError("Le mot de passe doit contenir au moins 8 caractères");
return;
}
if(Remember.isChecked()){
editor.putString("email",mEmail.getText().toString());
editor.putString("passowrd",mPassword.getText().toString());
editor.commit();
}else {
editor.putString("email", "");
editor.putString("passowrd", "");
editor.commit();
}
progressBar.setVisibility(View.VISIBLE);
// authenticate the user
fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
startActivity(new Intent(LoginActivity.this,PageTechnique.class));
}else {
Toast.makeText(LoginActivity.this, "Erreur ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
});
mCreateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,Register.class));
}
});
forgotTextLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetMail = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog= new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Réinitialiser votre mot de passe ?");
passwordResetDialog.setMessage("Entrer votre Email pour recevoir un lien de réinitialisation");
passwordResetDialog.setView(resetMail);
passwordResetDialog.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String mail = resetMail.getText().toString();
fAuth.sendPasswordResetEmail(mail).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(LoginActivity.this, "Un lien de réinitialisation vous a été envoyé", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, "Erreur ! le lien de réinitialisation n'a pas été envoyé" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("Non", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close the dialog
}
});
passwordResetDialog.create().show();
}
});
}
}
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bandeau_navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:itemBackground="#color/noir"
app:itemIconTint="#drawable/selector"
app:itemTextColor="#drawable/selector"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:menu="#menu/menu_navigation" />
<androidx.core.widget.NestedScrollView
android:id="#+id/scroll"
android:layout_width="0dp"
android:layout_height="0dp"
android:fillViewport="true"
app:layout_constraintBottom_toTopOf="#+id/bandeau_navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:id="#+id/view3"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#drawable/saaalogo" />
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="16dp"
android:background="#color/noir"
android:ems="10"
android:fontFamily="#font/futura_medium"
android:hint="Email"
android:padding="13dp"
android:textColor="#color/blanc"
android:textColorHint="#color/blanc"
android:textSize="20sp" />
<EditText
android:id="#+id/password1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="16dp"
android:background="#color/noir"
android:ems="10"
android:fontFamily="#font/futura_medium"
android:hint="Mot de passe"
android:inputType="textPassword"
android:padding="13dp"
android:textColor="#color/blanc"
android:textColorHint="#color/blanc"
android:textSize="20sp" />
<CheckBox
android:id="#+id/remember_me"
android:layout_width="377dp"
android:layout_height="34dp"
android:layout_marginStart="16dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:text="Se Souvenir de moi" />
<Button
android:id="#+id/loginBtn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="16dp"
android:background="#color/argent"
android:fontFamily="#font/futura_medium"
android:padding="15dp"
android:text="Se Connecter"
android:textSize="18sp" />
<TextView
android:id="#+id/createText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="16dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:fontFamily="#font/futura_medium"
android:padding="13dp"
android:text="Non inscrit ? Céer un compte"
android:textColor="#color/noir"
android:textSize="18sp"
android:visibility="visible" />
<TextView
android:id="#+id/forgotPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
android:fontFamily="#font/futura_medium"
android:text="Mot de passe oublié ?"
android:textColor="#color/noir"
android:textSize="18sp"
android:textStyle="bold" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:layout_marginBottom="20dp"
android:visibility="visible" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
How about this solution?
/////////////////To get Stored Data/////////////////////////////////
progressBar.setVisibility(View.GONE);
**boolean isRemember=sharedPreferences.getBoolean("remember_me",false);**
**if(isRemember){**
String email=sharedPreferences.getString("email","");
String passwords=sharedPreferences.getString("mot de passe","");
mEmail.setText(email);
mPassword.setText(passwords);
**Remember.setChecked(true);**
**}**
mLoginBtn.setOnClickListener(new View.OnClickListener() {
......
if(Remember.isChecked()){
**editor.putBoolean("remember_me",true);**
editor.putString("email",mEmail.getText().toString());
editor.putString("passowrd",mPassword.getText().toString());
editor.commit();
}else {
I am creating an android application where when in the front page i have a register button and a sign in button.Whenever i click on the sign in button it shows a dialog box but whenever i click on the register button it doesn't work.And i have checked the logcat also it doesn't throw any error.So please can anyone help me to figure out the error?
MainActivity.java
package com.example.vishal.uberclone;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import com.example.vishal.uberclone.Model.User;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.rengwuxian.materialedittext.MaterialEditText;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class MainActivity extends AppCompatActivity{
Button btnSignIn,btnRegister;
RelativeLayout rootLayout;
FirebaseAuth auth;
FirebaseDatabase db;
DatabaseReference users;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Arkhip_font.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_main);
auth = FirebaseAuth.getInstance();
db=FirebaseDatabase.getInstance();
users = db.getReference("Users");
btnRegister = (Button)findViewById(R.id.btnRegister);
btnSignIn = (Button) findViewById(R.id.btnSignIn);
rootLayout =(RelativeLayout) findViewById(R.id.rootLayout);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showRegisterDialog();
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showLoginDialog();
}
});
}
private void showRegisterDialog() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("REGISTER");
dialog.setMessage("Please use email to register");
LayoutInflater inflater = LayoutInflater.from(this);
View register_layout = inflater.inflate(R.layout.layout_register, null);
final MaterialEditText edtEmail = register_layout.findViewById(R.id.edtEmail);
final MaterialEditText edtPassword = register_layout.findViewById(R.id.edtPassword);
final MaterialEditText edtName = register_layout.findViewById(R.id.edtName);
final MaterialEditText edtPhone = register_layout.findViewById(R.id.edtPhone);
dialog.setView(register_layout);
//Set button
dialog.setPositiveButton("REGISTER", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
if (TextUtils.isEmpty(edtEmail.getText().toString())) {
Snackbar.make(rootLayout, "Please enter email address", Snackbar.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(edtPassword.getText().toString())) {
Snackbar.make(rootLayout, "Please enter password", Snackbar.LENGTH_SHORT).show();
return;
}
if (edtPassword.getText().toString().length() < 6) {
Snackbar.make(rootLayout, "Password too short!!!", Snackbar.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(edtName.getText().toString())) {
Snackbar.make(rootLayout, "Please enter your name", Snackbar.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(edtPhone.getText().toString())) {
Snackbar.make(rootLayout, "Please enter phone number", Snackbar.LENGTH_SHORT).show();
return;
}
auth.createUserWithEmailAndPassword(edtEmail.getText().toString(),edtPassword.getText().toString())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
//Save user to db
User user = new User();
user.setEmail(edtEmail.getText().toString());
user.setName(edtName.getText().toString());
user.setPhone(edtPhone.getText().toString());
user.setPassword(edtPassword.getText().toString());
//Use email to key
users.child(user.getEmail())
.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Snackbar.make(rootLayout,"Registered successfully",Snackbar.LENGTH_SHORT)
.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Snackbar.make(rootLayout,"Failed"+e.getMessage(),Snackbar.LENGTH_SHORT)
.show();
}
});
}
});
dialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialog.show();
}
});
}
private void showLoginDialog() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("SIGN IN");
dialog.setMessage("Please use email to sign in");
LayoutInflater inflater = LayoutInflater.from(this);
View login_layout = inflater.inflate(R.layout.layout_login,null);
final MaterialEditText edtEmail = login_layout.findViewById(R.id.edtEmail);
final MaterialEditText edtPassword = login_layout.findViewById(R.id.edtPassword);
dialog.setView(login_layout);
dialog.setPositiveButton("SIGN IN", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
if (TextUtils.isEmpty(edtEmail.getText().toString())) {
Snackbar.make(rootLayout, "Please enter email address", Snackbar.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(edtPassword.getText().toString())) {
Snackbar.make(rootLayout, "Please enter password", Snackbar.LENGTH_SHORT).show();
return;
}
if (edtPassword.getText().toString().length() < 6) {
Snackbar.make(rootLayout, "Password too short!!!", Snackbar.LENGTH_SHORT).show();
return;
}
//Login
auth.signInWithEmailAndPassword(edtEmail.getText().toString(),edtPassword.getText().toString())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
startActivity(new Intent(MainActivity.this,Welcome.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Snackbar.make(rootLayout,"Failed"+e.getMessage(),Snackbar.LENGTH_SHORT).show();
}
});
}
});
dialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialog.show();
}
}
User.java
package com.example.vishal.uberclone.Model;
public class User {
private String email,password,phone,name;
public User(){
}
public User(String email, String password, String name, String phone){
this.email = email;
this.password = password;
this.name = name;
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Welcome.java
package com.example.vishal.uberclone;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Welcome extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rootLayout"
android:background="#drawable/background"
tools:context="com.example.vishal.uberclone.MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="U B E R"
android:textSize="36sp"
android:textAlignment="center"
android:textColor="#android:color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="PARTNER"
android:textAlignment="center"
android:textColor="#android:color/white"
android:textSize="14sp" />
</LinearLayout>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:text="LOOKING FOR THE RIDER APP?"
android:textAlignment="center"
android:textColor="#color/bottomText"
android:textSize="12sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="16dp"
android:layout_above="#+id/text">
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:textColor="#android:color/white"
android:background="#drawable/btn_signn_in_background"
android:layout_height="wrap_content"
android:layout_marginRight="6dp"
android:id="#+id/btnSignIn"
android:text="SIGN IN"/>
<Button
android:id="#+id/btnRegister"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_weight="1"
android:background="#drawable/btn_register_background"
android:text="REGISTER"
android:textColor="#color/btnRegister" />
</LinearLayout>
</RelativeLayout>
layout_login.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="20dp">
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtEmail"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Email"
android:inputType="textEmailAddress"
android:textColor="#color/colorPrimary"
android:textColorHint="#color/colorPrimary"
android:textSize="20sp"
app:met_baseColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtPassword"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Password"
android:inputType="textPassword"
android:textColor="#color/colorPrimary"
android:textColorHint="#color/colorPrimary"
android:textSize="20sp"
app:met_baseColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"/>
</LinearLayout>
</android.support.v7.widget.CardView>
layout_register.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="20dp">
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtEmail"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Email"
android:inputType="textEmailAddress"
android:textColor="#color/colorPrimary"
android:textColorHint="#color/colorPrimary"
android:textSize="20sp"
app:met_baseColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtPassword"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Password"
android:inputType="textPassword"
android:textColor="#color/colorPrimary"
android:textColorHint="#color/colorPrimary"
android:textSize="20sp"
app:met_baseColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtName"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Name"
android:inputType="text"
android:textColor="#color/colorPrimary"
android:textColorHint="#color/colorPrimary"
android:textSize="20sp"
app:met_baseColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtPhone"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="Phone"
android:inputType="phone"
android:textColor="#color/colorPrimary"
android:textColorHint="#color/colorPrimary"
android:textSize="20sp"
app:met_baseColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"/>
</LinearLayout>
</android.support.v7.widget.CardView>
You are calling dialog.show(); inside OnClickListener from positiveButton. You must call it outside it:
private void showRegisterDialog() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("REGISTER");
dialog.setMessage("Please use email to register");
LayoutInflater inflater = LayoutInflater.from(this);
View register_layout = inflater.inflate(R.layout.layout_register, null);
final MaterialEditText edtEmail = register_layout.findViewById(R.id.edtEmail);
final MaterialEditText edtPassword = register_layout.findViewById(R.id.edtPassword);
final MaterialEditText edtName = register_layout.findViewById(R.id.edtName);
final MaterialEditText edtPhone = register_layout.findViewById(R.id.edtPhone);
dialog.setView(register_layout);
//Set button
dialog.setPositiveButton("REGISTER", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
if (TextUtils.isEmpty(edtEmail.getText().toString())) {
Snackbar.make(rootLayout, "Please enter email address", Snackbar.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(edtPassword.getText().toString())) {
Snackbar.make(rootLayout, "Please enter password", Snackbar.LENGTH_SHORT).show();
return;
}
if (edtPassword.getText().toString().length() < 6) {
Snackbar.make(rootLayout, "Password too short!!!", Snackbar.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(edtName.getText().toString())) {
Snackbar.make(rootLayout, "Please enter your name", Snackbar.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(edtPhone.getText().toString())) {
Snackbar.make(rootLayout, "Please enter phone number", Snackbar.LENGTH_SHORT).show();
return;
}
auth.createUserWithEmailAndPassword(edtEmail.getText().toString(),edtPassword.getText().toString())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
//Save user to db
User user = new User();
user.setEmail(edtEmail.getText().toString());
user.setName(edtName.getText().toString());
user.setPhone(edtPhone.getText().toString());
user.setPassword(edtPassword.getText().toString());
//Use email to key
users.child(user.getEmail())
.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Snackbar.make(rootLayout,"Registered successfully",Snackbar.LENGTH_SHORT)
.show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Snackbar.make(rootLayout,"Failed"+e.getMessage(),Snackbar.LENGTH_SHORT)
.show();
}
});
}
});
}
});
dialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
dialog.show();
}