Comparing EditText with EditText values - java

Does anyone know what's wrong with my code, I'm trying to compare the input in my edit text field to ensure their equal value before it creates an account.
//compare the fields contents
if(editTextPassword.equals(editTextReEnterPassword)) {
//they are equal
//Creating a new user
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
finish();
startActivity(new Intent(getApplicationContext(), Home.class));
} else{
Toast.makeText(Register.this, "Could not register... please try again", Toast.LENGTH_SHORT).show();
}
}
});
}else {//they are not equal
Toast.makeText(Register.this, "Passwords do not match... please try again", Toast.LENGTH_SHORT).show();
}

You have to get the text value of the edit text.
So, really, you can not do editText.equals()
You would do something like this..
String editTextPasswordString = editTextPassword.getText().toString().trim();
String editTextReEnterPasswordString = editTextReEnterPassword.getText().toString().trim();
if(editTextPasswordString.equals(editTextReEnterPasswordString)) {
//code
}

First you need to get the value from EditText using the method getText().toString(), like this:
String newPassword= editTextReEnterPassword.getText().toString();
For more information about the method, please check the follow link:
Get Value of EditText
After that, you need to compare the previous string editTextPassword with the new one created, which is the result of the method getText(), editTextReEnterPassword.
So your final code, should be like this:
String newPassword = editTextReEnterPassword.getText().toString();
String atualPassword = editTextPassword.getText().toString();
if(atualPassword.equals(newPassword))
{
...
}
else
{
...
}

Try:
if(editTextPassword.getText().toString().equals(editTextReEnterPassword.getText().toString()))
EditText is not a String

Related

Android studio not catching value from editText box

I would like to compare the Id that the user has inputted with the Id from the database as a login process. However, when I run the code after filling all the ID and password, the application returns that inputted ID and inputted pw are empty. What's the problem?
It happens because
final String inputId = editId.getText().toString();
final String inputPw = editPw.getText().toString();
These strings are initialized at the beginning in the onCreate() method.
When you click the button the buttonLogIn.setOnClickListener is executed with the same values initialized (empty values).
You have to get the new values from the EditText views.
buttonLogIn.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
//...
String user = editId.getText().toString();
String psw = editPw.getText().toString();
//..
if (!TextUtils.isEmpty(user)&& !TextUtils.isEmpty(psw)){ ... }
}
});
As mentioned by #Andy in the comments, you have to change also the check on firebase because the method is asynchronous.
if (TextUtils.isEmpty(user)&& TextUtils.isEmpty(psw)){
Toast.makeText(LoginScreen.this, "Complete all fields", Toast.LENGTH_SHORT).show();
} else {
//Firebase check
....
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//....
//Check the values here
if (userId.equals(inputId)) && userPw.equals(inputPw)){...}
}
}
You need to get the value from the edit text after the text has been updated:
if (!TextUtils.isEmpty(editId.getText().toString())&& !TextUtils.isEmpty(editPw.getText().toString()))...

Android app crashes when trying to use variable [duplicate]

#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.screenlocked);
//Retrieve stored ID
final String STORAGE = "Storage";
SharedPreferences unique = getSharedPreferences(STORAGE, 0);
LoginID = unique.getString("identifier", "");
//Retrieve stored phone number
final String phoneNumber = unique.getString("PhoneNumber", "");
phoneView = (TextView) findViewById(R.id.phone);
phoneView.setText(phoneNumber.toString());
//Retrieve user input
input = (EditText) findViewById(R.id.editText1);
userInput = input.getText().toString();
//Set login button
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
compareID();
}
});
}
public void compareID(){
if (userInput.equals(LoginID)){
//phone screen unlocked
//continue
Toast.makeText(ScreenLockActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
else{
count += 1;
input.setText("");
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
}
}
I am developing a login activity and I would like to record down how many times the user tried to login, so every time there is a login attempt the count will increment by one... but when i run the activity, this error appears in my logcat:
android.content.res.Resources$NotFoundException: String resource ID #0x1,
Can someone help me solve this problem?
Here is your mistake:
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
the makeText you are trying to invoke here, is the makeText that takes as second parameter a resId. See here for more info. Since you want to print the count value, you have to convert it in a String.
String value = String.valueOf(count);
Toast.makeText(ScreenLockActivity.this, value, Toast.LENGTH_SHORT).show();
This line should be inside onClick() or compareID():
userInput = input.getText().toString();

how to keep alert dialog open if user not provide the whole information

i have create a custom dialog where user will provide four information necessary from user , but if user click any button of alert dialog with out providing full information, the dialog is close, i want that alert not close unless the user provide full information
this is Custom alert dialog
enter image description here
this is java code for custom alert dialog
final ExtraFunction ef = new ExtraFunction(mContext);
final String PhoneNumber = holder.bdContactNumber.getText().toString();
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View promptsView = layoutInflater.inflate(R.layout.dialog_contact_for_blood, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setView(promptsView);
final EditText etSubject = (EditText) promptsView.findViewById(R.id.etSubject);
etSubject.setText(holder.bdBloodgroup.getText().toString());
final EditText etNumber_Bottles = (EditText) promptsView.findViewById(R.id.etNumber_Bottles);
final EditText etRequired_At = (EditText) promptsView.findViewById(R.id.etRequired_At);
final EditText etContact_number = (EditText) promptsView.findViewById(R.id.etContact_number);
alertDialogBuilder.setCancelable(false).setPositiveButton(R.string.send_message, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// get user input and set it to result
// edit text
String Subject = etSubject.getText().toString();
String Number_Bottles = etNumber_Bottles.getText().toString();
String Required_At = etRequired_At.getText().toString();
String Contact_number = etContact_number.getText().toString();
String blood_message = ""+Subject+" Blood "+Number_Bottles+" in Quantity is urgently required at "+Required_At+". Kindly contact at "+Contact_number+". Thanks.\n" + "("+R.string.app_name+")";
if(etNumber_Bottles.length()==0 && etRequired_At.length()==0 && etContact_number.length()==0)
{
Toast.makeText(mContext, "Please Enter All Values....", Toast.LENGTH_SHORT).show();
return;
}
else
{
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(PhoneNumber, null, blood_message, null, null);
Toast.makeText(mContext, R.string.success_message, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, R.string.failed_message + PhoneNumber, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
// ef.SendSmsFunction(PhoneNumber,blood_message);
}
}).setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
i search but not clear about my problem
You did some wrong validation
if(etNumber_Bottles.length()==0 && etRequired_At.length()==0 && etContact_number.length()==0)
{
Toast.makeText(mContext, "Please Enter All Values....", Toast.LENGTH_SHORT).show();
return;
}
as this validation works only when all the field empty instead of && operator you should use OR operator and take the string value of editText dont use length value direct on edit text first type cast to string than get the length. You can take use length method or equals method for this like below.
You can use this.
if(etNumber_Bottles.getText().toString().tolength()==0 || etRequired_At.getText().toString().length()==0 || etContact_number.getText().toString().length()==0)
{
Toast.makeText(mContext, "Please Enter All Values....", Toast.LENGTH_SHORT).show();
return;
}
Or by equals method:
if(etNumber_Bottles.getText().toString().equals("") || etRequired_At.getText().toString().equals("") || etContact_number.getText().toString().equals(""))
{
Toast.makeText(mContext, "Please Enter All Values....", Toast.LENGTH_SHORT).show();
return;
}
setOnShowListener may solve your problem:
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setMessage("Messsage")
.setPositiveButton(android.R.string.ok, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(final DialogInterface dialog) {
Button buttonOk = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
if (buttonOk != null) {
buttonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Write what you want to do on button click
}
});
}
}
});
Courtesy of this.
By the way, take a look on EditText#setError instead of yours Toast.makeText. Looks much more pretty!
P.P.S. I have changed my answer. You have to create AlertDialog and define setOnShowListener and your dialog will not closed on the button click. Is it what you desire?
Bro you need to learn how to validate view look at this example -https://stacktips.com/tutorials/android/edittext-validation-in-android-example
and https://www.excella.com/insights/how-do-i-validate-an-android-form and https://stackoverflow.com/a/33072633/4741746
there are some library provide easy way of validation one you can prefer is https://github.com/ragunathjawahar/android-saripaar
Best of luck

Android EditText Value Error?

I'm testing out some stuff on android as a beginner and was trying to grab value entered in a EditText when a button was clicked , then compare it to a string value that I defined inside the class, then use if (EditText == stringDefined) else () , but my code always jumps on the else part even if the correct text is entered, any help is appreciated. Here is the code :
Button mButton;
EditText mEdit1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final String user = "admin";
mButton = (Button)findViewById(R.id.BTN_login);
mEdit1 = (EditText)findViewById(R.id.editText1);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
String userEntered = mEdit1.getText().toString().trim();
Intent intent = new Intent(Login.this, Success.class);
if(userEntered == user){
startActivity(intent);
}
else{
AlertDialog.Builder errAlert = new AlertDialog.Builder(Login.this);
errAlert.setTitle("Wrong Credentials");
errAlert.setMessage("Wrong username");
errAlert.setCancelable(true);
errAlert.show();
}
}
});
}
Use equals method :
if(userEntered.equals(user)){
startActivity(intent);
}
== is used to compare primitive types and equals() method of java.lang.String class compares contents.

Toast isn't working, can't see why not

So I'm trying to write an activity that has two spinners and a button, when the two spinners are selected and the button pressed it'll take you to another activity. Except for one combination, which should produce a Toast saying that you can't do this.
Anyway, this is the code:
public void onClick(View v) {
String spinnerchoice1 = ("spinner1Value");
String spinnerchoice2 = ("spinner2Value");
if((spinnerchoice1.equals("Walking")) && (spinnerchoice2.equals("Hiking"))){
Toast.makeText(getBaseContext(), "I'm sorry, this is not possible.", Toast.LENGTH_LONG).show();
}else{
Intent i = new Intent(GetDirections.this.getApplicationContext(), DirectionDisplay.class);
i.putExtra("spinner1Value", transportSpinner.getSelectedItem().toString());
i.putExtra("spinner2Value", locationSpinner.getSelectedItem().toString());
GetDirections.this.startActivity(i);
}
}
Can anyone tell me where I'm going wrong?
Thanks
You are comparing two hard-coded strings, the if condition will never execute. Change the code to:
public void onClick(View v) {
String transport = transportSpinner.getSelectedItem().toString();
String location = locationSpinner.getSelectedItem().toString();
if ("Walking".equals(transport) && "Hiking".equals(location)) {
Toast.makeText(getBaseContext(), "I'm sorry, this is not possible.", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(GetDirections.this.getApplicationContext(), DirectionDisplay.class);
i.putExtra("spinner1Value", transport);
i.putExtra("spinner2Value", location);
GetDirections.this.startActivity(i);
}
}
If this is your actual code then your if is never going to evaluate to true because you are setting the strings to values that are not "Walking" and "Hiking"
these two lines:
String spinnerchoice1 = ("spinner1Value");
String spinnerchoice2 = ("spinner2Value");
need to be something like this (assuming that you spinner just contains String objects and not some other type):
String spinnerchoice1 = transportSpinner.getSelectedItem().toString();
String spinnerchoice2 = locationSpinner.getSelectedItem().toString();

Categories

Resources