I'm completely new to android and development too. I created a page to take the email EditText, password EditText and signup button. So here how can I link this EditText to code to verify the entered values in both EditText is valid?
Below is the code that i'm trying to use.
public void isEmailValid(View view) {
this.view = view;
EditText editText = (EditText) findViewById(R.id.editText);
if (editText.getText().toString().matches("[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+") && editText.length() > 0) {
editText.setText("valid email");
} else {
editText.setText("invalid email");
}
}
Thanks in advance.
If you want to evaluate email address after clicking the button you might set a click listener for your button and do it :
Button yourButton = (Button) findViewById(R.id.your_button);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
evaluateEmail();
}
});
and here is your method for evaluation :
private void evaluateEmail() {
EditText editText = (EditText) findViewById(R.id.editText);
if (editText.getText().toString().matches("[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+") && editText.length() > 0) {
//it is valid
} else {
//it is not valid
}
}
Try this code:
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) &&
android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
How can we perform Email Validation on edittext in android ? I have gone through google & SO but I didn't find out a simple way to validate it. follow link..
How should I validate an e-mail address?
You can use Android Patterns class to perform match for your email regex.
Patterns.EMAIL_ADDRESS.matcher(editText.getText().toString()).matches();
Related
i am trying to create a login system on android studio using java, i have tried a piece of code i have found and modifies it to my own program- i am getting errors that the tutorial cannot explain and would appreciate if someone could tell me what i'm doing wrong.
on line 10 under username it says expression expected
The else statement says there should be an if but as you can see there is ?
public void LoginButton(){
UserName = findViewById(R.id.UserName);
userPassword = findViewById(R.id.userPassword);
userPin = findViewById(R.id.userPin);
GoBtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UserName.getText().toString().equals("user");// here i would preferably link to a database but do to time restaitns i have modeled it with user
userPassword.getText().toString().equals("pass");
{
Toast.makeText(MainActivity.this, "Username and password is correct",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, StudentActivity.class);
startActivity(intent);
}
else {
Toast.makeText(MainActivity.this,"Username and password is NOT correct",
Toast.LENGTH_SHORT).show();
}
}
I need this to lead the user to the next activty if the input is correct but so far i cannot get it to run due to the errors.
Issues
You can't use a semicolon (;) right after if statement because an empty ; is also considered a statement.
If Statement is incorrect: It has to be a valid statement
Many braces ({ and }) are missing
Here is a sample code
public void LoginButton() {
UserName = findViewById(R.id.UserName);
userPassword = findViewById(R.id.userPassword);
userPin = findViewById(R.id.userPin);
GoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UserName.getText().toString().equals("user") &&
userPassword.getText().toString().equals("pass")) {
// use your code
} else {
// use your code
}
}
});
}
Suggestion: Please read more Java
your if condition syntax is wrong you need to use AND operator(&&).
change these lines
if (UserName.getText().toString().equals("user");
userPassword.getText().toString().equals("pass");
to
if((UserName.getText().toString().equals("user")) && (userPassword.getText().toString().equals("pass")))
In my application I have a booking system which allows users to book tee times for specific times during the day. When a booking has been completed the details are saved to my Firebase and the user can then close the alert dialog. When the alert dialog is then closed the button which was clicked is then made unusable. Problem is that when the user leaves the booking activity and comes back the button is then useable, and if a different user then accesses the page the button is also able to be clicked as well.
How do I solve this problem?
Should I be saving the UID of the user in the 9am child ?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
findViewById(R.id.profilebtn).setOnClickListener(this);
findViewById(R.id.booking9am).setOnClickListener(this);
book9am = (Button)findViewById(R.id.booking9am);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.profilebtn:
finish();
startActivity(new Intent(Booking.this, ProfileActivity.class));
break;
case R.id.booking9am:
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(Booking.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_booking,null);
final EditText mPlayer1 = (EditText) mView.findViewById(R.id.player1);
final EditText mPlayer2= (EditText) mView.findViewById(R.id.player2);
final EditText mPlayer3 = (EditText) mView.findViewById(R.id.player3);
final EditText mPlayer4 = (EditText) mView.findViewById(R.id.player4);
final EditText mTime = (EditText) mView.findViewById(R.id.timeedit);
final Button mBookingbtn = (Button) mView.findViewById(R.id.bookingbtn);
mBookingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String player1= mPlayer1.getText().toString().trim();
String player2= mPlayer2.getText().toString().trim();
String player4= mPlayer4.getText().toString().trim();
String player3= mPlayer3.getText().toString().trim();
if (player1.isEmpty()) {
mPlayer1.setError("Please enter player 1");
mPlayer1.requestFocus();
return;
}
if (player2.isEmpty()) {
mPlayer2.setError("Please enter player 2");
mPlayer2.requestFocus();
return;
}
if (player3.isEmpty()) {
mPlayer3.setError("Please enter player 2");
mPlayer3.requestFocus();
return;
}if (player2.isEmpty()) {
mPlayer4.setError("Please enter player 2");
mPlayer4.requestFocus();
return;
}
String playerone = mPlayer1.getText().toString();
String playertwo = mPlayer2.getText().toString();
String playerthree = mPlayer3.getText().toString();
String playerfour = mPlayer4.getText().toString();
String teetime= mTime.getText().toString().trim();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Booking").child("9am");
Map newPost = new HashMap();
newPost.put("playerone",playerone);
newPost.put("playertwo",playertwo);
newPost.put("playerthree",playerthree);
newPost.put("playerfour",playerfour);
newPost.put("teetime",teetime);
current_user_db.setValue(newPost);
Toast.makeText(Booking.this, "Booking Confirmed", Toast.LENGTH_SHORT).show();
book9am.setClickable(false);
}
});
mBuilder.setNeutralButton("Close ", new DialogInterface.OnClickListener() { // define the 'Cancel' button
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
}
}
In your onCreate method -
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Booking").child("9am");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
book9am.setClickable(false);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
well there could be multiple approaches to this problem.
One is to set a Boolean variable in local storage Shared preference against every user....
Once your click the button set the value to true and when u come back in app check if variable is true then disable button..
Second solution Store the varible against every user on firebase and check(recommended since user can change phone)
Before showing the activity you will have to make a request to your firebase to check if the booking has been completed and depending on the result make the button enabled or not.
findViewById(R.id.booking9am).setOnClickListener(this) instead of this use:-
book9am = (Button)findViewById(R.id.booking9am);
book9am.setOnClickListener(this);
and instead of book9am.setClickable(false) set book9am.setEnable(false);
OR
If you want button disable on some conditions then it can be managed at server side also.
There are two approaches to your problem, depending on your needs.
First, is saving the button's state locally (on the client side), which means that after removing and re-installing the app for example, the state will be reset as well.
In order to save the button's state "forever", you should save the wanted state on the device, and this is what SharedPreferences is made for.
This is a good example of using it.
Here is how you should implement it in your code:
public static void set_isButtonClickable(Context ctx, Boolean bool) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean("BUTTON_CLICKABLE_STATE", bool);
editor.commit();
}
public static boolean getPrefIsFirstLaunch(Context ctx) {
return getSharedPreferences(ctx).getBoolean("BUTTON_CLICKABLE_STATE",false);
}
Second, is saving the button's state on the server side. Removing and re-installing the app obviously won't change its state. Make each user a variable which called "button_state" and change it as needed:
I'm new to stackoverflow and android, sorry if i'm wrong. I am trying to check the text fields is empty or not, when the text field is empty, upload button should show please enter title and when user enters the text then only it should upload the image. After entering title then also it again shows the toast.
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (title1.matches("")){
Toast.makeText(getApplicationContext(), "Please enter the Title and Category", Toast.LENGTH_SHORT).show();
} else if(description1.matches("")){
Toast.makeText(getApplicationContext(), "Please Select Category", Toast.LENGTH_SHORT).show();
} else {
flag = 1;
// uploading the file to server
new UploadFileToServer().execute();
}
}
});
Any help would be appreciated.
To check for empty fields, use
if(TextUtils.isEmpty(editText.getText().toString())) {
// do something
}
or if you want to check if string is empty or null use -
if(TextUtils.isEmpty(stringToCheck) {
// do something
}
try this.
Place this code in your button onClickListener:
String mText = mEditText.getText().toString();
if(TextUtils.isEmpty(mText)){
//Do what you want(Edittext is NULL)
}else{
//Do what you want(Not NULL)
}
Try to get value from your edittext like below:
Globally declare variable : -
String editvalue;
In onCreate() :-
EditText youredittext = (EditText)findViewById(R.id.youredittextid);
editvalue = youredittext.getText.toString().trim();
Now in your condition check :
if(editvalue.isEmpty() || editvalue == null){
// Do what you want when editText's value is null or empty
}else{
}
You can also use
TextUtils.isEmpty(CharSequence str)
for empty and null string check.
Returns true if the string is null or 0-length
I am working on a login page in an Android App.
As you know, the app must check if the username and password are valid, and then grant the user access to the application.
I have used the following code:
...
EditText un = (EditText) findViewById(R.id.username1);
EditText pw = (EditText) findViewById(R.id.password1);
String u = un.getText().toString();
String p = pw.getText().toString();
//////// Now on the click of the Login Button:
public void onClickL (View view){
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
else ///////Display a warning message: Try again
}
when I run this code this only executes the else part. why its not executing the if part? what should I do ?
The reason is that you are fetching the EditText's value while declaring the EditText. Actually you nee to fetch the Text from EditText while clicking on the button, hence you need to move you code to onClick() method like below,
#Override
public void onClick (View view)
{
String u = un.getText().toString();
String p = pw.getText().toString();
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
{
....
}
else ///////Display a warning message: Try again
{
....
}
}
please try this:
public void onClickL (View view){
u = un.getText().toString();
p = pw.getText().toString();
if ( u.equals("Android") && p.equals("1234") ) /////// move to a new activity
{
}
else ///////Display a warning message: Try again
{
}
}
try Following code
need to clear space in username if it is available.
public void onClick (View view){
String username = un.getText().toString().trim();
String password = pw.getText().toString();
if ((username.equals("Android")) && (password.equals("1234"))) {
//do something
} else{
//do something
}
}
Try this..
get the text inside Click function like below
public void onClick (View view){
String u = un.getText().toString().trim();
String p = pw.getText().toString().trim();
if ((u.equals("Android")) && (p.equals("1234"))) {
//do something
}
else{
//do something
}
}
Please how can i apply this code to my android application. I am making an application that gives access to the User by entering the correct password.
I seem to be getting an error with the Console
public static void main (String args[]) throws IOException {
Console c=System.console();
String login = c.readLine("Enter your login: ");
char [] oldPassword = c.readPassword("Enter your old password: ");
if (verify(login, oldPassword)) {
boolean noMatch;
do {
char [] newPassword1 =
c.readPassword("Enter your new password: ");
char [] newPassword2 =
c.readPassword("Enter new password again: ");
noMatch = ! Arrays.equals(newPassword1, newPassword2);
if (noMatch) {
c.format("Passwords don't match. Try again.%n");
} else {
change(login, newPassword1);
c.format("Password for %s changed.%n", login);
}
Arrays.fill(newPassword1, ' ');
Arrays.fill(newPassword2, ' ');
} while (noMatch);
}
Arrays.fill(oldPassword, ' ');
}
//Dummy change method.
static boolean verify(String login, char[] password) {
// this method always returns true in this example.
// modify this method to verify password according to your rules.
return true;
}
//Dummy change method.
static void change(String login, char[] password) {
// modify this method to change password according to your rules.
}
}
Yes you can re-use your verify and change apis for android but you have discard whatever in the main method.
On Android, you will be creating an Activity having three EditText (for hide user text use android:inputType="textPassword"), one for each.
Old Password
New Password
New Password Again
Then you ll have one button call it Change Password. To this Change Password button you can add onClickListenr. When user presses this Change Password button, you will fetch the text values from EditText and then user your verify and change apis to do the actual work.
You can optionally choose a Cancel button too.
Below is how screen will look:
Snippet of handling the Change button:
// Declared in your Activity class.
EditText editTextOldPass;
EditText editTextNewPass;
EditText editTextNewPassAgain;
String login = "";
public void onCreate(Bundle savedInstanceState) {
editTextOldPass = (EditText) findViewById(R.id.editTextOldPass);
editTextNewPass = (EditText) findViewById(R.id.editTextNewPass);
editTextNewPassAgain = (EditText) findViewById(R.id.editTextNewPassAgain);
Button buttonChange = (Button) findViewById(R.id.buttonChange);
buttonChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editTextNewPass.getText().equals(editTextNewPassAgain)) {
if (verify(login, editTextOldPass.getText().toString().toCharArray()))
change(login, editTextNewPass.getText().toString().toCharArray());
} else {
Log.i("PasswordActivity", "Passwords don't match. Try again.");
}
}
});
}