Print a toast if specific parameter is correct - android

I'm trying to print a toast msg if the username and password is equal to admin i try this code but the toast msg says it's error and the logcat doesn't show anything
code i tried
public class login extends AppCompatActivity {
DatabaseHelper db;
EditText username,password;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = new DatabaseHelper(this);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
login = findViewById(R.id.login);
adminLogin();
}
public void toast(Context context, String string){
Toast.makeText(this,string, Toast.LENGTH_SHORT).show();
}
public void adminLogin(){
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(username.getText().toString() == "admin" || password.getText().toString() == "admin"){
toast(login.this,"Done");
}
else{
toast(login.this,"Error");
}
}
});
}
}

You should not use == to compare String in java, rather you should use .equals method on String. So your logic should be as follow:
if(username.getText().toString().equals("admin") || password.getText().toString().equals("admin")){
toast(login.this,"Done");
}

Related

Firebase Phone number authentication error, Phone number not readable

When I enter a phone number into my EditText field and press login, the java code has to validate if the editText field is empty or not. So after entering my phone no., the if(!phonenumber.isempty()) is always false and the else statement is executed, that is "Please enter number" Toast
Here is my compelete code:
public class User_login extends AppCompatActivity {
private EditText editTextphone;
private Button otp_login;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
otp_login = (Button) findViewById(R.id.otp_login);
editTextphone = (EditText) findViewById(R.id.editTextphone);
String phoneNumber = editTextphone.getText().toString().trim();
mAuth = FirebaseAuth.getInstance();
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!phoneNumber.isEmpty()){
if(phoneNumber.length() == 10){
progressBar.setVisibility(View.VISIBLE);
otp_login.setVisibility(View.INVISIBLE);
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+91" + phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(User_login.this)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull #org.jetbrains.annotations.NotNull PhoneAuthCredential phoneAuthCredential) {
progressBar.setVisibility(View.GONE);
otp_login.setVisibility(View.VISIBLE);
}
#Override
public void onVerificationFailed(#NonNull #org.jetbrains.annotations.NotNull FirebaseException e) {
progressBar.setVisibility(View.GONE);
otp_login.setVisibility(View.VISIBLE);
Toast.makeText(User_login.this,"Some error occured" + e.getMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onCodeSent(#NonNull #org.jetbrains.annotations.NotNull String s, #NonNull #org.jetbrains.annotations.NotNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
Intent intent = new Intent(getApplicationContext(),opt_verify.class);
intent.putExtra("phone", editTextphone.getText().toString());
intent.putExtra("mVerificationId", s);
startActivity(intent);
}
};
}else{
Toast.makeText(User_login.this,"Please enter complete number",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(User_login.this,"Please enter mobile number",Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
if(mAuth.getCurrentUser() != null){
startActivity(new Intent(this, home_user.class));
}
}
}
You should get the EditText input in the onClick Listner, only then you could get the latest inputted value from the edittext.
ie,
String phoneNumber = editTextphone.getText().toString().trim();
should be called inside :
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = editTextphone.getText().toString().trim(); //like this
if(!phoneNumber.isEmpty()){
There is a problem in your logic. The reason is that you are getting text before clicking the button meanwhile when the onCreate method runs it gets the value form the EditText. But you need get the value when you click the button each time.
Try this code:
otp_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = editTextphone.getText().toString().trim();
if (!phoneNumber.isEmpty()) {
if (phoneNumber.length() == 10) {
//you logic or code here
}
}
}
}

login Button redirecting to mainpage instead of user page in android Studio app with firebase realtime database

public class loginActivity extends AppCompatActivity {
TextView signup;
TextInputLayout phone,pass;
Button btn_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
signup = findViewById(R.id.txt_signup);
phone = findViewById(R.id.phone);
pass = findViewById(R.id.pass);
btn_login = findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginUser(view);
}
});
}
private boolean validatePhone(){
String p = phone.getEditText().getText().toString();
if(p.isEmpty()){
phone.setError("field is empty!");
return false;
}
else {
phone.setError(null);
phone.setErrorEnabled(false);
return true;
}
}
private boolean validatePass(){
String p = pass.getEditText().getText().toString();
if(p.isEmpty()){
pass.setError("field is empty!");
return false;
}
else {
pass.setError(null);
pass.setErrorEnabled(false);
return true;
}
}
public void loginUser(View v){
if(!validatePhone() | !validatePass()){
return;
}
else {
isUser();
}
}
private void isUser(){
final String appPhone = Objects.requireNonNull(phone.getEditText()).getText().toString().trim();
final String appPass = Objects.requireNonNull(pass.getEditText()).getText().toString().trim();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users");
Query checkUser = databaseReference.orderByChild("phone").equalTo(appPhone);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
phone.setError(null);
phone.setErrorEnabled(false);
String fbasePass = dataSnapshot.child("pass").getValue(String.class);
assert fbasePass != null;
if(fbasePass.equals(appPass)){
phone.setError(null);
phone.setErrorEnabled(false);
// String uPhone = dataSnapshot.child(appPhone).child("phone").getValue(String.class);
String uPhone = dataSnapshot.child("phone").getValue(String.class);
String uAadhar = dataSnapshot.child("aadhar").getValue(String.class);
String ucity = dataSnapshot.child("city").getValue(String.class);
String ufname = dataSnapshot.child("fname").getValue(String.class);
String uemail = dataSnapshot.child("email").getValue(String.class);
Intent intent = new Intent(getApplicationContext(),usrHome.class);
intent.putExtra("phone",uPhone);
intent.putExtra("aadhar",uAadhar);
intent.putExtra("city",ucity);
intent.putExtra("fname",ufname);
intent.putExtra("email",uemail);
startActivity(intent);
}
else {
pass.setError("Wrong password");
pass.requestFocus();
}
}
else {
phone.setError("Please Create Account First");
phone.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
when i click login button it is pause for sometime and automatically redirecting to main page of my application.
i was using data from firebase realtime database in login activity.
please help me about this.. i wasted my 2 days to solve this problem but nothing is working.
in case if you have another code that can fulfill this requirement than please let me know.
You are starting the LoginActivity before the Firebase actually logout the user. Try to add a FirebaseAuth.AuthStateListener and just start the LoginActivity when the listener is trigged. See this post: Firebase signout is not leading to the correct activity

Null pointer exception when login fields are empty - Firebase

I have this code where the user enters his credentials and logs in.
public class LoginActivity extends AppCompatActivity {
private static final String TAG = LoginActivity.class.getSimpleName();
private FirebaseAuth mAuth;
private Toolbar mToolbar;
private TextInputEditText mLoginEmail;
private TextInputEditText mLoginPassword;
private Button mLoginBtn;
private Button mForgotPass;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mToolbar = findViewById(R.id.login_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Login");
mAuth = FirebaseAuth.getInstance();
mProgress = new ProgressDialog(this);
mLoginEmail = (TextInputEditText)findViewById(R.id.login_email);
mLoginPassword = (TextInputEditText)findViewById(R.id.login_password);
mLoginBtn = (Button)findViewById(R.id.login_create_btn);
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = mLoginEmail.getText().toString();
String pass = mLoginPassword.getText().toString();
if(!TextUtils.isEmpty(email) || !TextUtils.isEmpty(pass)){
mProgress.setTitle("Logging in");
mProgress.setMessage("Please wait while we check your credentials");
mProgress.setCanceledOnTouchOutside(false);
mProgress.show();
loginUser(email,pass);
}
}
});
mForgotPass = (Button)findViewById(R.id.login_forgot_password);
mForgotPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this,ForgotPasswordActivity.class);
startActivity(i);
}
});
}
private void loginUser(final String email, final String pass) {
mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
mProgress.dismiss();
sendToMain();
} else {
mProgress.hide();
Toast.makeText(LoginActivity.this, "Can not login", Toast.LENGTH_SHORT).show();
Log.d(TAG, String.valueOf(task.getException()));
}
}
});
}
private void sendToMain() {
Intent mainIntent = new Intent(LoginActivity.this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
To achieve a login procedure I call the signInWithEmailAndPassword(email,pass) method as you see above. Just for validation purposes I want to have a toast saying that you should fill both email and password fields. As it is now, I get an exception when I click the login button. How to fix that?
This is the exception.
at com.google.android.gms.common.internal.zzbq.zzgm(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(Unknown Source)
at theo.tziomakas.news.LoginActivity.loginUser(LoginActivity.java:90)
at theo.tziomakas.news.LoginActivity.access$300(LoginActivity.java:22)
at theo.tziomakas.news.LoginActivity$1.onClick(LoginActivity.java:70)
Thanks,
Theo.
Found your error, the following:
if(!TextUtils.isEmpty(email) || !TextUtils.isEmpty(pass))
should be an && and not a ||:
if(!TextUtils.isEmpty(email) && !TextUtils.isEmpty(pass))
You want both to be not null to call your login.

How to to disable the send button if my fields are not filled using a textwatcher?

I'm having a hard time figuring out a solution to this situation. I need assistance, I am trying to disable the send button if my fields are not filled using a textwatcher. Here is part of the code:
public class Main5Activity extends AppCompatActivity {
TextView shoppinglist, fullname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
fullname = (TextView) findViewById(R.id.fullname);
shoppinglist = (TextView) findViewById(R.id.shoppinglist);
public void send(View v) {
new Send().execute();
}
}
Try this, and use EditText, TextView is not inputable:
editText1.addTextChangedListener(this);
imageButton.setEnable(false);
#Override
public void afterTextChanged(Editable s) {
if (s.toString().equals("")) {
imageButton.setEnabled(false);
} else {
imageButton.setEnabled(true);
}
}
Actually you don't need to use the textwatcher for disabling send button. All you could do is disable the send button in onCreate method within an if loop.
Note: Use EditText instead of TextView for taking inputs from user.
public class Main5Activity extends AppCompatActivity {
EditText shoppinglist, fullname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
fullname = findViewById(R.id.fullname);
button1 = (Button) findViewById(R.id.buttsave);
shoppinglist = findViewById(R.id.shoppinglist);
final String username = fullname.getText().toString();
final String shopList = shoppinglist.getText().toString();
if (TextUtils.isEmpty(username)&&TextUtils.isEmpty(shopList)) {
fullname.setError("Please enter your fullname");
shoppinglist.setError("Please select shopping list");
button1.setEnabled(false);
}
else {
button1.setEnabled(true);
}
//close onCreate here
}
public void send(View v) {
// it is not possible to enable the send button here because you are already
// executing the send method. So it should have already been enabled.
new Send().execute();
}
Again, if there is a necessity of using the textwatcher then do this:
public class Main5Activity extends AppCompatActivity implements TextWatcher {
EditText shoppinglist, fullname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
fullname = findViewById(R.id.fullname);
button1 = (Button) findViewById(R.id.buttsave);
shoppinglist = findViewById(R.id.shoppinglist);
fullname.addTextChangedListener(this);
shoppinglist.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
final String username = fullname.getText().toString();
final String shopList = shoppinglist.getText().toString();
if (TextUtils.isEmpty(username)&&TextUtils.isEmpty(shopList)) {
fullname.setError("Please enter your fullname");
shoppinglist.setError("Please select shopping list");
button1.setEnabled(false);
}
else {
button1.setEnabled(true);
}
}
public void send(View v) {
button1.setEnabled(true);
new Send().execute();
}
Hope this helps. Reply in comment if you still have any doubts.

Button is clickable but doesn't work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I have this code but when I'm trying it on my phone doesn't do anything..
I tried the version on firebase website too but it doesn't work. I would really appreciate if you can help me guys!
I think that this is the problem
Can someone help me with it?
public class LoginActivity extends AppCompatActivity {
public Firebase mFirebase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
mFirebase = new Firebase("https://kip.firebaseio.com");
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
}
public void onClickLogin(View v){
final String email = ((EditText) findViewById(R.id.email)).getText().toString();
final String password =((EditText) findViewById(R.id.password)).getText().toString();
mFirebase.createUser(email, password, new Firebase.ResultHandler() {
#Override
public void onSuccess() {
mFirebase.authWithPassword(email, password, null);
System.out.println("Successfully created user account!");
}
#Override
public void onError(FirebaseError firebaseError) {
mFirebase.authWithPassword(email, password, null);
System.out.println("There was an error connecting!");
}
});
}
}
Here is my XML
<Button
android:layout_width="300dp"
android:layout_height="wrap_content"
android:background="#drawable/button_login"
android:text="#string/login"
android:textColor="#android:color/white"
android:textSize="16sp"
android:id="#+id/button"
android:layout_below="#+id/password"
android:layout_centerHorizontal="true"
android:layout_marginTop="75dp"
android:onClick="onClickLogin"
android:clickable="true" />
Try with:
public class LoginActivity extends AppCompatActivity {
public Firebase mFirebase;
Button button = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
mFirebase = new Firebase("https://kip.firebaseio.com");
requestWindowFeature(Window.FEATURE_NO_TITLE);
button.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
final String email = ((EditText) findViewById(R.id.email)).getText().toString();
final String password =((EditText) findViewById(R.id.password)).getText().toString();
mFirebase.createUser(email, password, new Firebase.ResultHandler() {
#Override
public void onSuccess() {
mFirebase.authWithPassword(email, password, null);
System.out.println("Successfully created user account!");
}
#Override
public void onError(FirebaseError firebaseError) {
mFirebase.authWithPassword(email, password, null);
System.out.println("There was an error connecting!");
}
});
}
});
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
}
}
This is the final code and it works!!
protected EditText mEmail;
protected EditText mPassword;
protected Button mLogin;
protected Button mRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Firebase.setAndroidContext(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mLogin = (Button) findViewById(R.id.Login);
mRegister = (Button) findViewById(R.id.Register);
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Firebase ref = new Firebase("https://kip.firebaseio.com");
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
ref.authWithPassword(email, password, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
Intent activity = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(activity);
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
// there was an error
}
});
}
});
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Firebase ref = new Firebase("https://kip.firebaseio.com");
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
ref.createUser(email, password, new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Successfully created user account with uid: " + result.get("uid"));
}
#Override
public void onError(FirebaseError firebaseError) {
// there was an error
}
});
}
});
}
}

Categories

Resources