I wrote following code for login but when I type "\" after email-id, it accepts and log in successfully (it doesn't accepts any other symbols or characters only accepts "\").
I don't want that it login with "\".`
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.main);
WiztangoBaseApplication.InitDialogBox(WiztangoActivity.this);
this.pref = PreferenceManager.getDefaultSharedPreferences(this);
loginStatus = (TextView)findViewById(R.id.login_status);
register = (Button) findViewById(R.id.btnregister);
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RegisterIntent();
}
});
login = (Button) findViewById(R.id.btlogin);
password = (EditText) findViewById(R.id.txtPwd);
username = (EditText) findViewById(R.id.txtemail);
saveLoginCheckBox = (CheckBox)findViewById(R.id.saveLoginCheckBox);
pref = getSharedPreferences(Constants.PREFS_NAME,
MODE_PRIVATE);
String usernamestr = pref.getString(Constants.PREF_USERNAME, "");
String passwordsharestr = pref.getString(Constants.PREF_PASSWORD,
"");
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLogin = pref.getBoolean("saveLogin", false);
if (saveLogin == true) {
username.setText(usernamestr);
password.setText(passwordsharestr);
saveLoginCheckBox.setChecked(true);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
//Constants.clearInfo();
getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE)
.edit()
.putString(Constants.PREF_USERNAME,
username.getText().toString())
.putString(Constants.PREF_PASSWORD,
password.getText().toString())
.putString(Constants.PREF_CHECKED, "TRUE")
.commit();
if (username.getText().toString().trim().equals("")) {
username.setError(Html
.fromHtml("Please Enter Username"));
username.requestFocus();
} else if (password.getText().toString().trim()
.equals("")) {
password.setError(Html
.fromHtml("Please Enter Password"));
password.requestFocus();
} else {
if (Constants
.checkInternetConnection(WiztangoActivity.this)) {
Constants.userpass = password.getText()
.toString();
new AuthenticData().execute();
} else {
WiztangoBaseApplication.ShowThisDialog("Error",
"Please check internet connection.");
}
if (saveLoginCheckBox.isChecked()) {
prefEditor.putBoolean("saveLogin", true);
prefEditor.putString(Constants.PREF_USERNAME,
username.getText().toString());
prefEditor.putString(Constants.PREF_PASSWORD,
password.getText().toString());
saveLoginCheckBox.setChecked(true);
prefEditor.commit();
} else {
SharedPreferences mPreferences = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor=mPreferences.edit();
editor.remove(Constants.PREF_USERNAME);
editor.remove(Constants.PREF_PASSWORD);
editor.commit();
}
}
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.e("Exception In Wiztango/", e.toString());
e.printStackTrace();
}
}
Inbuilt Patterns Provides Email Validation like:
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailStr).matches() && !TextUtils.isEmpty(emailStr)) {
emailEditText.setError("Invalid Email");
emailEditText.requestFocus();
}
Heyy, check this answer here: https://stackoverflow.com/a/7882950/1739882
It says:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
You can use this code for check is Valid Email or not:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
Best Approach
Validate email and isEmpty in one method.
public final static boolean isValidEmail(CharSequence target)
{
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
Try out the below method to validate the Email address.
private boolean validateEmail(EditText editText, String p_nullMsg, String p_invalidMsg)
{
boolean m_isValid = false;
try
{
if (p_editText != null)
{
if(validateForNull(editText,p_nullMsg))
{
Pattern m_pattern = Pattern.compile("([\\w\\-]([\\.\\w])+[\\w]+#([\\w\\-]+\\.)+[A-Za-z]{2,4})");
Matcher m_matcher = m_pattern.matcher(editText.getText().toString().trim());
if (!m_matcher.matches() && editText.getText().toString().trim().length() > 0)
{
m_isValid = false;
editText.setError(p_invalidMsg);
}
else
{
m_isValid = true;
}
}
else
{
m_isValid = false;
}
}
else
{
m_isValid = false;
}
}
catch(Throwable p_e)
{
p_e.printStackTrace(); // Error handling if application crashes
}
return m_isValid;
}
Try this code:--
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
Related
When I run the codes, it does not show any error. I have no problem to login as guardian but when I try to login as elderly it couldn't and I don't know what's the problem. What I want is when a user input the username and password, it will validate from database and direct the user according to different user type.
Segment codes of Login.java:
private Boolean validateUsername() {
String val = username.getEditText().getText().toString();
if (val.isEmpty()) {
username.setError("Field cannot be empty");
return false;
} else {
username.setError(null);
username.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = password.getEditText().getText().toString();
if (val.isEmpty()) {
password.setError("Field cannot be empty");
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
public void loginUser(View view) {
//validate login info
if (!validateUsername() || !validatePassword()) {
return;
} else {
isUser();
}
}
private void isUser() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("user").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String input1 = username.getEditText().getText().toString();
String input2 = password.getEditText().getText().toString();
if (dataSnapshot.child(input1).exists()) {
if (dataSnapshot.child(input1).child("password").getValue(String.class).equals(input2)) {
if (active.isChecked()) {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Guardian");
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Elderly");
startActivity(new Intent(Login.this, dashboardUser.class));
}
} else {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardUser.class));
}
}
} else {
password.setError("Wrong Password");
password.requestFocus();
}
} else {
username.setError("No such User exist");
username.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
protected void onStart() {
super.onStart();
if (preferences.getDataLogin(this)) {
if (preferences.getDataAs(this).equals("Guardian")) {
startActivity(new Intent(this, dashboardGuardian.class));
finish();
} else {
startActivity(new Intent(this, dashboardUser.class));
finish();
}
}
}
}
Codes of Register.java:
public class Register extends AppCompatActivity {
//Variables
TextInputLayout regUsername, regEmail, regPhoneNo, regPassword;
RadioGroup radioGroup;
RadioButton selectedElderly, selectedGuardian;
Button regBtn, regToLoginBtn;
UserHelperClass helperClass;
int i = 0;
FirebaseDatabase rootNode;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Hooks to all xml elements in activity_register.xml
regUsername = findViewById(R.id.reg_username);
regEmail = findViewById(R.id.reg_email);
regPhoneNo = findViewById(R.id.reg_phoneNo);
regPassword = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regToLoginBtn = findViewById(R.id.reg_login_btn);
radioGroup = findViewById(R.id.radio_type);
selectedGuardian = findViewById(R.id.radioGuardian);
selectedElderly = findViewById(R.id.radioElderly);
helperClass = new UserHelperClass();
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validateUsername() && validateEmail() && validatePhoneNo() && validateUserType() && validatePassword() == true) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
} else {
validateUsername();
validateEmail();
validatePhoneNo();
validateUserType();
validatePassword();
}
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("user");
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
String username = regUsername.getEditText().getText().toString();
String password = regPassword.getEditText().getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(username).setValue(helperClass);
}
});
regToLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
}
});
}
private Boolean validateUsername() {
String val = regUsername.getEditText().getText().toString();
String noWhiteSpace = "\\A\\w{4,20}\\z";
if (val.isEmpty()) {
regUsername.setError("Field cannot be empty");
return false;
} else if (val.length() >= 15) {
regUsername.setError("Username too long");
return false;
} else if (!val.matches(noWhiteSpace)) {
regUsername.setError("White space is not allowed");
return false;
} else {
regUsername.setError(null);
regUsername.setErrorEnabled(false);
return true;
}
}
private Boolean validateEmail() {
String val = regEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
regEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
regEmail.setError("Invalid email address");
return false;
} else {
regEmail.setError(null);
return true;
}
}
private Boolean validatePhoneNo() {
String val = regPhoneNo.getEditText().getText().toString();
if (val.isEmpty()) {
regPhoneNo.setError("Field cannot be empty");
return false;
} else {
regPhoneNo.setError(null);
return true;
}
}
private Boolean validateUserType() {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(this, "Please select user type", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
}
private Boolean validatePassword() {
String val = regPassword.getEditText().getText().toString();
String passwordVal = "^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white space
".{4,}" + //at least 4 characters
"$";
if (val.isEmpty()) {
regPassword.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
regPassword.setError("Password is too weak");
return false;
} else {
regPassword.setError(null);
regPassword.setErrorEnabled(false);
return true;
}
}
public void registerUser(View view) {
if (!validateUsername() | !validatePassword() | !validatePhoneNo() | !validateEmail() | validateUserType()) {
return;
}
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(String.valueOf(i + 1)).setValue(helperClass);
}
}
Database structure
If you post your database structure that would be more helpful.
As per your code.
you have two children in input1
'radioGuardian' and 'radioElderly'
have you added both values on registration? Or it will be null. And it will produce nullPointEx.
Hence the issue is here!
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
Try to change it to:-
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
helperClass.setRadioGuardian("NA");
} else {
helperClass.setRadioGuardian(m2);
helperClass.setRadioElderly("NA");
}
I have gone through many tutorials with API.AI But didn't get the exact solution. My requirement is simply:- user will send some command using voice or text and get that commands in my application and execute some method.
API.AI
Actions on Google
Tutorial of Google Assistant
First of all you need to train your model on API.AI to respond upon some text given to the model.
Some code with API.AI FYI:
//Initialize Service
private void initService(final LanguageConfig selectedLanguage) {
try {
final AIConfiguration.SupportedLanguages lang = AIConfiguration.SupportedLanguages.fromLanguageTag(selectedLanguage.getLanguageCode());
final AIConfiguration config = new AIConfiguration(selectedLanguage.getAccessToken(),
lang,
AIConfiguration.RecognitionEngine.System);
aiDataService = new AIDataService(this, config);
} catch (Exception e) {
e.printStackTrace();
}
}
//Send request method where you can put user typed text to get the result from API.AI
private void sendRequest(final String textToSend, final int flag) {
Log.w(TAG, "Sending" + textToSend);
final AsyncTask<String, Void, AIResponse> task = new AsyncTask<String, Void, AIResponse>() {
private AIError aiError;
#Override
protected void onPreExecute() {
super.onPreExecute();
showHideProgressBar(true);
if (mVoiceRecorder != null) {
mVoiceRecorder.pauseRecording();
}
}
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
String event = params[1];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
if (!TextUtils.isEmpty(event)) {
request.setEvent(new AIEvent(event));
}
final String contextString = params[2];
RequestExtras requestExtras = null;
if (!TextUtils.isEmpty(contextString)) {
final List<AIContext> contexts = Collections.singletonList(new AIContext(contextString));
requestExtras = new RequestExtras(contexts, null);
}
try {
Log.i("API AI Request", "" + request.toString());
return aiDataService.request(request, requestExtras);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
showHideProgressBar(false);
speechSentStatus = false;
okSentStatus = false;
if (response != null) {
onResult(response, flag, textToSend);
} else {
onError(aiError);
}
}
};
if (flag == OPEN_COMPLAIN_CODE) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == OPEN_DIAGNOSIS_CODE) {
task.execute("", Config.Events[1], Config.Events[1]);
} else if (flag == Constants.OPEN_MEDICATION_CODE) {
task.execute("", Config.Events[2], Config.Events[2]);
} else if (flag == Constants.OPEN_LABTEST_CODE) {
task.execute("", Config.Events[3], Config.Events[3]);
} else if (flag == Constants.COMPLAINTS_ADDED) {
task.execute("", Config.Events[0], Config.Events[0]);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
task.execute("", Config.Events[1], Config.Events[1]);
} else {
task.execute(textToSend, null, "");
}
}
//Based on result you can handle the business logic
private void onResult(final AIResponse response, final int flag, final String textToSend) {
runOnUiThread(new Runnable() {
#Override
public void run() {
apiAiResponseCounter = apiAiResponseCounter + 1;
isLast = false;
final Result result = response.getResult();
Log.w(TAG, "" + result.getFulfillment().getSpeech());
if (flag == Constants.COMPLAINTS_ADDED) {
//method you want to execute on receiving certain text from model
send(textToSend.toLowerCase(), DONTTEXT);
} else if (flag == Constants.DIAGNOSIS_ADDED) {
send(textToSend.toLowerCase(), DONTTEXT);
} else {
String error = "";
final String speech = result.getFulfillment().getSpeech();
if (speech.contains("?")) {
if (!result.getAction().equalsIgnoreCase("input.unknown")) {
if (result.getAction().equalsIgnoreCase(Config.Actions[5]) && result.isActionIncomplete() == false) {
//DONOTHING
} else {
digiMessage(speech, YESNO);
}
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
} else {
if (speech.equalsIgnoreCase("Please help me the intake duration of the medication")) {
digiMessage(speech, ChatMessageAdapter.DURATION);
} else if (speech.equalsIgnoreCase("Please provide the daily routine for the medication intake")) {
digiMessage(speech, ChatMessageAdapter.FREQUENCY);
} else {
digiMessage(speech, ChatMessageAdapter.OTHER_MESSAGE);
}
}
if (result.getAction().equalsIgnoreCase(Config.Actions[4]) || result.getAction().equalsIgnoreCase(Config.Actions[5])) {
if (result.isActionIncomplete() == true) {
playSpeech(speech);
} else {
speechBuffer = "";
speechBuffer = speech;
}
} else {
if (result.getAction().equalsIgnoreCase(Config.Actions[11])) {
isLast = true;
if (mVoiceRecorder != null) {
stopVoiceRecording();
}
} else {
playSpeech(speech);
}
}
}
}
});
if (flag == Constants.COMPLAINTS_ADDED || flag == Constants.DIAGNOSIS_ADDED) {
Log.w(TAG, "Skipped");
} else {
inflateUI(response.getResult());
}
}
I have made a fragment in which I am validating a Register form, it works fine sometime but after few seconds the app stops without showing any message nor I have any error log...I don't know what happens.
Here is my code:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register, container, false);
RegUsername = (EditText) view.findViewById(R.id.RegUsername);
RegEmailId = (EditText) view.findViewById(R.id.RegEmailId);
RegPhoneNo = (EditText) view.findViewById(R.id.RegPhoneNo);
RegPassword = (EditText) view.findViewById(R.id.RegPassword);
RegisterButton = (Button) view.findViewById(R.id.Register);
RegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Register(); }})};
return view; }
private void Register() {
initialize();
if (!registerfail()) {
Toast.makeText(getActivity(), "Registration failed! || Try Again", Toast.LENGTH_SHORT).show();
} else {
registerok();
}
}
private void registerok() {
Toast.makeText(getActivity(), "Welcome " + Username, Toast.LENGTH_SHORT);
}
private boolean registerfail() {
boolean validation = true;
if (Username.isEmpty() || Username.length() > 25) {
RegUsername.setError("Invalid username");
validation = false;
}
if (EmailId.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(EmailId).matches()) {
RegEmailId.setError("Invalid EmailId");
validation = false; }
}
if (PhoneNo.isEmpty()) {
RegPhoneNo.setError("Invalid PhoneNo.");
validation = false; }
}
if (Password.isEmpty()) {
RegPassword.setError("Invalid Password");
validation = false;}
}
return validation; }
private void initialize() {
Username = RegUsername.getText().toString().trim();
EmailId = RegEmailId.getText().toString().trim();
PhoneNo = RegPhoneNo.getText().toString().trim();
Password = RegPassword.getText().toString().trim(); }}
//set validation = false if any if condition is failed
private boolean registerfail() {
boolean validation = true;
if (Username.isEmpty() || Username.length() > 25) {
RegUsername.setError("Invalid username");
validation = false;
}
if (EmailId.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(EmailId).matches()) {
RegEmailId.setError("Invalid EmailId");
validation = false;
}
if (PhoneNo.isEmpty()) {
RegPhoneNo.setError("Invalid PhoneNo.");
validation = false;
}
if (Password.isEmpty()) {
RegPassword.setError("Invalid Password");
validation = false;
}
return validation;
}
try this way my friend
String emailAddress = RegEmailId.getText().toString().trim();
if (RegPassword.getText().toString().length() < 6) {
RegPassword.setError(getString("password minimum contain 6 character"));
RegPassword.requestFocus();
}
if (RegPassword.getText().toString().equals("")) {
RegPassword.setError(getString("please enter password"));
RegPassword.requestFocus();
}
if (RegPhoneNo.getText().toString().equals("")) {
RegPhoneNo.setError(getString("please enter password"));
RegPhoneNo.requestFocus();
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches()) {
RegEmailId.setError(getString("please enter valid email address"));
RegEmailId.requestFocus();
}
if (RegEmailId.getText().toString().equals("")) {
RegEmailId.setError(getString("please enter email address"));
RegEmailId.requestFocus();
}
if (!emailAddress.equals("") &&
RegPassword.getText().toString().length() >= 6 &&
!RegPassword.getText().toString().trim().equals("")
&& android.util.Patterns.EMAIL_ADDRESS.matcher(emailAddress).matches() &&
!RegPhoneNo.getText().toString().equals("")&&
RegPhoneNo.getText().toString().length()>=10) {
// do your action
}
I want to start next activity after validation and I want to save the information in sharedpreferences successfully when i click submit button
public class Main2Activity extends AppCompatActivity implements SearchView.OnQueryTextListener {
EditText fullname, contact, emailaddress, address, password, repassword, username;
RadioGroup radiogroup;
Button submits,clear;
Toolbar toolbar;
SearchView mSearchView;
SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
pref = getSharedPreferences("myfile", Context.MODE_PRIVATE);
fullname = (EditText) findViewById(R.id.edittextfullname);
contact = (EditText) findViewById(R.id.edittextcontact);
emailaddress = (EditText) findViewById(R.id.edittextemailaddress);
address = (EditText) findViewById(R.id.edittextaddress);
password = (EditText) findViewById(R.id.edittextpassword);
repassword = (EditText) findViewById(R.id.edittextrepassword);
username = (EditText) findViewById(R.id.edittextusername);
radiogroup = (RadioGroup) findViewById(R.id.radiogroup);
submits = (Button) findViewById(R.id.submit);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.Title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
submits.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
final String name = fullname.getText().toString();
if (!isValidFullname(name)) {
fullname.setError("Invalid Name");
}
final String number = contact.getText().toString();
if (!isValidContact(number)) {
contact.setError("Invalid Contact");
}
final String email = emailaddress.getText().toString();
if (!isValidEmailaddress(email)) {
emailaddress.setError("Invalid Email Address");
}
final String addres = address.getText().toString();
if (!isValidAddress(addres)) {
address.setError("Invalid address");
}
final String pass = password.getText().toString();
final String rpassword = repassword.getText().toString();
if (pass.equals(rpassword) && rpassword.equals(pass)) {
} else {
password.setError("invalid");
repassword.setError("invalid");
}
final String uname = username.getText().toString();
if (!isValidUsername(uname)) {
username.setError("Invalid Username");
}
else {
Intent startNewActivity = new Intent(Main2Activity.this, DisplayActivity.class);
startActivity(startNewActivity);
}
SharedPreferences.Editor editor = pref.edit();
editor.putString("fullname",name);
editor.putString("contact",number);
editor.putString("emailaddress",email);
editor.putString("address",addres);
editor.putString("password",pass);
editor.putString("repassword",rpassword);
editor.putString("username",uname);
editor.apply();
Toast.makeText(Main2Activity.this, "Save succesful", Toast.LENGTH_LONG).show();
}
});
private boolean isValidContact(String number) {
if (number != null && number.length() == 10) {
return true;
}
return false;
}
private boolean isValidEmailaddress(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
private boolean isValidAddress(String addres) {
if (addres != null) {
return true;
}
return false;
}
private boolean isValidPassword(String pass) {
if (pass.equals(repassword) && repassword.equals(pass)) {
return true;
} else {
return false;
}
}
private boolean isValidUsername(String name) {
if (name != null && name.length() > 5) {
return true;
}
return false;
}
You should just put
SharedPreferences.Editor editor = pref.edit();
editor.putString("fullname",name);
editor.putString("contact",number);
editor.putString("emailaddress",email);
editor.putString("address",addres);
editor.putString("password",pass);
editor.putString("repassword",rpassword);
editor.putString("username",uname);
editor.apply();
In your
else {
Intent startNewActivity = new Intent(Main2Activity.this, DisplayActivity.class);
startActivity(startNewActivity);
}
Or do i missunderstand what you want to do ?
Hi In My application checking validation for email id and phone number but it's not validating both and simply it's saving into database.
I want to check the email id and phone number if it's both correct i want to do next process
Can any one please help me
ContactUs.java
public class ContactUs extends Activity
{
EditText fname1,lname1,mobile1,altmob1,email1,comment1;
String data="";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contactus);
fname1=(EditText) findViewById(R.id.fname);
lname1=(EditText) findViewById(R.id.lname);
mobile1=(EditText) findViewById(R.id.mobile);
altmob1=(EditText) findViewById(R.id.altno);
email1=(EditText) findViewById(R.id.email);
comment1=(EditText) findViewById(R.id.coment);
Button Send = (Button) findViewById(R.id.Send);
Send.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
String fname = fname1.getText().toString();
String lname = lname1.getText().toString();
String mobile = mobile1.getText().toString();
String altmob = altmob1.getText().toString();
String email = email1.getText().toString();
String comment = comment1.getText().toString();
if(fname.equals(""))
{
fname1.setError( "Please Enter First Name" );
}
else if(lname.equals(""))
{
lname1.setError( "Please Enter Last Name" );
}
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
isValidMobile(mobile);
}
else if(altmob.equals(""))
{
altmob1.setError( "Please Enter Altenative Mobile No." );
}
else if(email.equals(""))
{
email1.setError( "Please Enter EmailId" );
isValidMail(email);
}
else if(comment.equals(""))
{
comment1.setError( "Please Enter Your Comments here" );
}
else
{
try{
String queryString ="fname="+ fname
+"&lname="+lname+"&mobile="+mobile+ "&altmob="+altmob+"&email="+email+"&comment="+comment;
data = DatabaseUtility.executeQueryPhp("Contactform",queryString);
fname1.setText("");
lname1.setText("");
mobile1.setText("");
altmob1.setText("");
email1.setText("");
comment1.setText("");
Toast.makeText(
ContactUs.this,
"Message:Records Saved Sucessfully",
Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private boolean isValidMail(String email)
{
boolean check;
Pattern p;
Matcher m;
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
p = Pattern.compile(EMAIL_STRING);
m = p.matcher(email);
check = m.matches();
if(!check)
{
email1.setError("Not Valid Email");
}
return check;
}
private boolean isValidMobile(String mobile)
{
boolean check;
if(mobile.length() < 6 || mobile.length() > 13)
{
check = false;
mobile1.setError("Not Valid Number");
}
else
{
check = true;
}
return check;
}
there are edittext box with property email
android:inputType="textEmailAddress"
in your code
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
isValidMobile(mobile);
}
it check if email in blank then go to isValidMobile
so use
else if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
}
else if(!isValidMobile(mobile)){
// do somting
}
and similar for email
You are running your valid email check but ignoring the result. As long as you enter some text the call to save will work.
If you incorporate the return values from your is valid check methods, you can stop saving when those calls return false.
e.g.
if(mobile.equals(""))
{
mobile1.setError( "Please Enter Mobile No." );
}
else if(!isValidMobile(mobile))
{
mobile1.setError("Not Valid Number");
}
Try this for checking email:
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
For telephone number check:
public final static boolean isValidPhone(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.PHONE.matcher(target).matches();
}
}
And please update your code with as :
public class ContactUs extends Activity {
EditText fname1, lname1, mobile1, altmob1, email1, comment1;
String data = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactus);
fname1 = (EditText) findViewById(R.id.fname);
lname1 = (EditText) findViewById(R.id.lname);
mobile1 = (EditText) findViewById(R.id.mobile);
altmob1 = (EditText) findViewById(R.id.altno);
email1 = (EditText) findViewById(R.id.email);
comment1 = (EditText) findViewById(R.id.coment);
Button Send = (Button) findViewById(R.id.Send);
Send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String fname = fname1.getText().toString().trim();
String lname = lname1.getText().toString().trim();
String mobile = mobile1.getText().toString().trim();
String altmob = altmob1.getText().toString().trim();
String email = email1.getText().toString().trim();
String comment = comment1.getText().toString().trim();
if (fname.length() != 0) {
if (lname.length() != 0) {
if (mobile.length() != 0 && isValidMobile(mobile)) {
if (altmob.length() != 0 && isValidMobile(altmob)) {
if (email.length() != 0 && isValidMail(email)) {
if (comment.length() != 0) {
try {
String queryString = "fname="
+ fname + "&lname=" + lname
+ "&mobile=" + mobile
+ "&altmob=" + altmob
+ "&email=" + email
+ "&comment=" + comment;
data = DatabaseUtility
.executeQueryPhp(
"Contactform",
queryString);
fname1.setText("");
lname1.setText("");
mobile1.setText("");
altmob1.setText("");
email1.setText("");
comment1.setText("");
Toast.makeText(
ContactUs.this,
"Message:Records Saved Sucessfully",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
} else {
comment1.setError("Please Enter Your Comments here");
}
} else {
email1.setError("Please Enter Valid EmailId");
}
} else {
altmob1.setError("Please Enter Altenative Mobile No.");
}
} else {
mobile1.setError("Please Enter valid Mobile No.");
}
} else {
lname1.setError("Please Enter Last Name");
}
} else {
fname1.setError("Please Enter First Name");
}
}
});
}
private boolean isValidMail(String email) {
boolean check;
Pattern p;
Matcher m;
String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
p = Pattern.compile(EMAIL_STRING);
m = p.matcher(email);
check = m.matches();
if (!check) {
email1.setError("Not Valid Email");
}
return check;
}
private boolean isValidMobile(String mobile) {
boolean check;
if (mobile.length() < 6 || mobile.length() > 13) {
check = false;
mobile1.setError("Not Valid Number");
} else {
check = true;
}
return check;
}
}