I have a sign up form that asking the users to enter a username and a password twice, I want to don't submit the form and alert the user if he messes to fill any of the fields, but the button is not working in all cases, this is my code:
user = (EditText) this.findViewById(R.id.username);
pass = (EditText) this.findViewById(R.id.password);
pass2 = (EditText) this.findViewById(R.id.password2);
u = user.getText().toString();
p1 = pass.getText().toString();
p2 = pass2.getText().toString();
if(!(u.equals("")||p1.equals("")||p2.equals(""))){
btn = (Button) this.findViewById(R.id.register2);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!p1.equals(p2))
Toast.makeText(getApplicationContext(), "Passwords didn't match!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "Passwords match!", Toast.LENGTH_SHORT).show();
}
});
}
Remove this if condition line
if(!(u.equals("")||p1.equals("")||p2.equals(""))){
And put this inside the click lisner
if(!(u.equals("")||p1.equals("")||p2.equals(""))){
//Toast message please enter the username or pwd
return;
}
I found the ideal answer is make a method as follow:
boolean isEmpty(EditText e){
return e.getText().toString().trim().length() == 0;
}
Simple way is check the length of the EditText box content
EditText resultInput = (EditText)findViewById(R.id.result);
if(resultInput.getText().length() > 0)
// Edit Text is Empty
else
// Edit Text is Empty
if(!(user.getText().length() <= 0) & (pass.getText().length() <= 0) & (pass2.getText().length() <= 0))){
btn = (Button) this.findViewById(R.id.register2);
...
Related
*UPDATED*still haveing issues please if you see any errors please let me know, i would like to put my logcat in but i cant access it due to the errors .......I'm having issues with my login and registration mechanism. I'm probably doing something wrong, but when i try to test out the login my app crashes with the message "...has suddenly stopped." msg. Also, my textview that goes to my registration class isnt responding. Can some please help me?
I know there is probably a lot of errors, but be kind I'm new to this :)
If anyone is generous or just bored and wanted to personally help me out with issues please leave your email
Below is the code for my login class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(), SignUp.class);
startActivity(i);
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get The Reference Of Buttons
btnSignIn = (Button) findViewById(R.id.btnLogin);
}
// Methods to handleClick Event of Sign In Button
public void signIn(View V) {
try{
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
Button btnSignIn = (Button) dialog.findViewById(R.id.btnLogin);
}catch(Exception e){
Log.e("tag", e.getMessage());
}
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword = loginDataBaseAdapter
.getSingleEntry(username);
// check if the Stored password matches with Password entered by
// user
if (password.equals(storedPassword)) {
Toast.makeText(LoginScreen.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
} else {
Toast.makeText(LoginScreen.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
dialog.show();
}
}
#Override
public void startActivity(Intent intent) {
// TODO Auto-generated method stub
try{
super.startActivity(intent);
Intent mainpage = new Intent(LoginScreen.this, MainPage.class);
startActivity(mainpage);
finish();
}catch(Exception e){
Log.e("tag", e.getMessage());
}
}
#Override
protected void onDestroy() {
try{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
MY registration class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
// Listening to Login Screen link
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Closing registration screen
// Switching to Login Screen/closing register screen
finish();
// get Instance of Database Adapter
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get References of Views
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_confirmpassword = (EditText) findViewById(R.id.reg_confirmpassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String fullname = reg_fullname.getText().toString();
String username = reg_username.getText().toString();
String password = reg_password.getText().toString();
String email = reg_email.getText().toString();
String confirmPassword = reg_confirmpassword.getText()
.toString();
// check if any of the fields are vacant
if (username.equals("") || password.equals("")
|| confirmPassword.equals("")) {
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if (!password.equals(confirmPassword)) {
Toast.makeText(getApplicationContext(),
"Password does not match", Toast.LENGTH_LONG)
.show();
return;
} else {
// Save the Data in Database
loginDataBaseAdapter.insertEntry(username, password);
Toast.makeText(getApplicationContext(),
"Account Successfully Created ", Toast.LENGTH_LONG)
.show();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}}
The best way to know your code errors it's, put all your code in a block try-catch in all functions..
try{
//your code here
}catch(Exception e){
Log.e("tag", e.getMessage());
}
in Logcat will be apears in red color the errors of your code, "tag" it's a way to differentiate the erros like:
#Override
protected void onDestroy() {
try{
super.onDestroy();
loginDataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy - Error", e.getMessage());
}
}
I hope this helps...
I have an activity in which there are three EditTexts: First Name, Middle Name, Last Name, and a Submit button. If the user submits with a field blank, a different toast appears for different field. Here's is an example when button will be clicked!:
I'll assume you can figure out how to use a button listener yourself. Inside that button listener, you can use this code:
// create EditText references
EditText etFirstName = (EditText)findViewById(R.id.firstName);
EditText etMiddleName = (EditText)findViewById(R.id.middleName);
EditText etLastName = (EditText)findViewById(R.id.lastName);
// boolean variables that each represent whether or not the each field is blank
// if the EditText length is 0, it's true (blank); otherwise, it's false (filled)
boolean firstNameBlank = etFirstName.length() == 0;
boolean middleNameBlank = etMiddleName.length() == 0;
boolean lastNameBlank = etLastName.length() == 0;
if (firstNameBlank && middleNameBlank && lastNameBlank) {
// toast all three blank
}
else if (firstNameBlank && middleNameBlank) {
// toast just first and middle are blank
}
else if (firstNameBlank && lastNameBlank) {
// toast just first and last are blank
}
else if (middleNameBlank && lastNameBlank) {
// toast just middle and last are blank
}
else if (firstNameBlank) {
// toast just first is blank
}
else if (middleNameBlank) {
// toast just middle is blank
}
else if (lastNameBlank) {
// toast just last is blank
}
else {
// none are blank
}
Try this way
EditText e = (EditText)findViewById(R.id.EDITTEXT));
if(e.getText().length == 0){
//Show Toast
}else{
//continue your code
}
implement onClick() event of your submit button as below:
#Override
public void onClick(View view) {
super.onClick(view);
switch (view.getId()) {
case R.id.btnSubmit:
if(edtFirstName.getText().toString().length() < 1){
Toast.makeText(this, "please fill all boxes.",Toast.LENGTH_LONG).show();
}else if(edtSecondName.getText().toString().length() < 1){
Toast.makeText(this, "please fill middle name and last name.",Toast.LENGTH_LONG).show();
} else if(edtLastName.getText().toString().length() < 1){
Toast.makeText(this, "please fill last name.",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "please wait...processing.",Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
Here's the code snippet
s= e1.getText().toString();
iv1 = (ImageView) findViewById(R.id.imageView1);
iv1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(s.matches("")){
int time=2000;
Toast.makeText(Loadscreen.this, "Please specify the level", time).show();
}
else{
int str= Integer.valueOf(s);
if(str>0 && str<11){
calculate(str);
r2=new Random();
int nxt = r2.nextInt(2);
if(nxt==0){
//do some work
}
else{
//do some work
}
}
else{
int time=2000;
Toast.makeText(Loadscreen.this, "Enter a valid level", time).show();
}
}
}
});
Control never goes to the else block. The output on the screen is the text of the Toast with the comment "Please specify the level".
Please suggest why else part is not executed?
probably you are not getting the correct result while getting the text from edit text
write this line in onclick method before any comparison
s= e1.getText().toString();
When I click on button in my program without entering data it shows both errors parallely (I have Highlighted in below prog). here i need to get only one error at a time i mean when it is null it has show appropriate one.vice versa..
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v==findViewById(R.id.button1)) {
et1 = (EditText) findViewById(R.id.editText1);
if(et1.getText()!=null ) {
try {
radius = Double.valueOf(et1.getText().toString());
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
if(radius==0.0) {
Toast.makeText(getApplicationContext(), "Value cannot be 0", Toast.LENGTH_SHORT).show();
}
try {
output = (double) Math.round(Math.PI * radius * radius);
String s = Double.toString(output);
tv1.setText(s);
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please enter correct value", Toast.LENGTH_SHORT).show();
}
}
}
});
do not make things more complicated as they actually are. You can be sure that a correct value was entered without any try/catch blocks. Possible approach:
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Pattern p = Pattern.compile("([0-9]*)");
if (et1.getText().toString().trim().length() > 0) {
Matcher m = p.matcher(et1.getText().toString().trim());
if (m.matches()) {
radius = Double.valueOf(et1.getText().toString());
output = (double) Math.round(Math.PI * radius
* radius);
tv1.setText(Double.toString(output));
} else
Toast.makeText(getApplicationContext(),
"incorrect value", Toast.LENGTH_SHORT)
.show();
} else
Toast.makeText(getApplicationContext(),
"input is empty", Toast.LENGTH_SHORT).show();
break;
default:
}
}
});
In the above code you check if there was any text entered. The second if checks whether the input is numeric using a java regex. When both requirements are met you can be sure the output is calculated correctly.
BTW, using switch-case is a better approach for click listeners
Hey guys I have an Activity with some EditText fields.
The user needs to fill up all the text fields before pressing the save Button.
Here is what I thought would work. I checked the texts entered in the EditText fields, if the text is not null, then the respective data is saved in
the data base, but if the text is null, a Toast is displayed displaying a message to re enter the text. here's the code:
account_Number.setText(null);
customer_Number.setText(null);
account_Holder.setText(null);
bank_Name.setText(null);
branch_Name.setText(null);
branch_Address.setText(null);
Ifsc.setText(null);
Micr.setText(null);
current_Balance.setText(null);
AddAccount = (Button) findViewById(R.id.addAccount);
AddAccount.setOnClickListener(this);
}
// only after all the fields have been filled, should the message data added
// successfully be displayed.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.addAccount:// try making the user enter in all the fields
boolean work = true;
if (account_Number.getText() != null
&& customer_Number.getText() != null
&& account_Holder.getText() != null
&& bank_Name.getText() != null
&& branch_Name.getText() != null
&& branch_Address.getText() != null
&& Ifsc.getText() != null && Micr.getText() != null
&& current_Balance.getText() != null) {
try {
String accountNumber = account_Number.getText().toString();
String customerNumber = customer_Number.getText()
.toString();
String accountHolder = account_Holder.getText().toString();
String bankName = bank_Name.getText().toString();
String branchName = branch_Name.getText().toString();
String branchAddress = branch_Address.getText().toString();
String ifsc = Ifsc.getText().toString();
String micr = Micr.getText().toString();
String currentBalance = current_Balance.getText()
.toString();
DatabaseClass entry = new DatabaseClass(AddnewAccount.this);
entry.open();
entry.createEntry(accountNumber, customerNumber,
accountHolder, bankName, branchName, branchAddress,
ifsc, micr, currentBalance);
} catch (Exception e) {
work = false;
Dialog message = new Dialog(this);
message.setTitle("Error");
String error = e.toString();
TextView tv = new TextView(this);
tv.setText(error);
message.setContentView(tv);
message.show();
} finally {
Toast message = Toast.makeText(AddnewAccount.this,
"Data Added Successfully", Toast.LENGTH_SHORT);
message.show();
Intent goBackHome = new Intent(AddnewAccount.this,
AccountManagerActivity.class);
startActivity(goBackHome);
finish();
}
} else {
Toast message = Toast.makeText(AddnewAccount.this, // not getting executed
"Please Fill All The Fields", Toast.LENGTH_LONG);
message.show();
Intent refill = new Intent(AddnewAccount.this,
AddnewAccount.class);
startActivity(refill);
finish();
}
break;
}
}
A blank EditText field does not return null for getText(), but rather returns "".
Just check if .getText().toString().trim().equals("") for each field.
check like,,,
String a_number = account_Number.getText().tostring().trim();
String c_number = customer_Number.getText().tostring().trim();
if(TextUtils.isEmpty(a_number) || TextUtils.isEmpty(c_number)){
Toast.makeText(AddnewAccount.this,
"Please Fill All The Fields", Toast.LENGTH_LONG).show();
}else{
//Nothing is empty...
}