Validating and Saving data to SharedPreference - android

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 ?

Related

When clicking Register button with empty field app crashes with error "NumberFormatException"

my register is working fine, but i want to validate when the fields(EditText) are empty, if i click register the app crashes and if i leave an empty field it crashes too..
public class register extends AppCompatActivity {
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
builder = new AlertDialog.Builder(register.this);
final EditText etAge = (EditText) findViewById(R.id.etAge);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
final String password = etPassword.getText().toString();
//test of error
if (name.equals("") || username.equals("") || age == 0 || password.equals("")) {
builder.setTitle("Something Went Wrong");
builder.setMessage("Please fill in all the fileds").setPositiveButton("OK", null).create().show();
} else {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(register.this, login.class);
register.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(register.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(register.this);
queue.add(registerRequest);
}
}
});
}
Integer age =null;
if(!etAge.getText().toString().trim().equals(""))
{
age=Integer.parseInt(etAge.getText().toString());
}
final String password = etPassword.getText().toString();
//test of error
if (name.equals("") || username.equals("") || age == null || password.equals("")) {
builder.setTitle("Something Went Wrong");
builder.setMessage("Please fill in all the fileds").setPositiveButton("OK", null).create().show();
return ;
}

How to get user data with SharedPreferences from RegisterActivity

i programmed my register activity to get my user details and store it with SharePreferences
Now , im trying to get those values stored in the data to log in in my app but it seems im missing something, when i put anything in my edittexts in my login layout it logs in without checking the user
RegisterActivity.class
public class RegistrarUsuario extends AppCompatActivity {
private Button mBtnRegistrarUsuario;
private TextView mRegistrarTxt;
private EditText mUsername,mPassword,mSecondPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrar_usuario);
mRegistrarTxt = (TextView) findViewById(R.id.titulo2);
mUsername = (EditText) findViewById(R.id.nombreUsuario);
mPassword = (EditText) findViewById(R.id.primeraContraseña);
mSecondPassword = (EditText) findViewById(R.id.segundaContraseña);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mRegistrarTxt.setTypeface(fuente);
mBtnRegistrarUsuario = (Button) findViewById(R.id.btnRegistrarUsuario);
mBtnRegistrarUsuario.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String secondpassword = mSecondPassword.getText().toString().trim();
if(username.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese un usuario.", Toast.LENGTH_SHORT).show();
}
else if(password.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese contraseña.", Toast.LENGTH_SHORT).show();
}
else if(secondpassword.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Confirme su contraseña.", Toast.LENGTH_SHORT).show();
}
else if(password.equals(secondpassword)){
SharedPreferences.Editor editor = preference.edit();
editor.putString("Username",username);
editor.putString("Password",password);
editor.putString("SecondPassword",secondpassword);
editor.commit();
finish();
Toast.makeText(RegistrarUsuario.this, "Usuario creado con exito!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegistrarUsuario.this,PantallaPrincipal.class);
startActivity(intent);
}
else{
Toast.makeText(RegistrarUsuario.this, "No coinciden las contraseñas.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
** LoginActivity.class**
public class MainActivity extends AppCompatActivity {
private EditText mUsername,mPassword;
private Button mLoginBtn,mBtnRecuperar,mBtnRegistrar;
private TextView mTextView;
private static String usuario ="admin";
private static String contraseña="123";
private final String KEY_USERNAME = "username";
private final String KEY_PASSWORD = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = (EditText) findViewById(R.id.usuario);
mPassword = (EditText) findViewById(R.id.contraseña);
mLoginBtn = (Button) findViewById(R.id.btnIngresar);
mTextView = (TextView) findViewById(R.id.titulo);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mTextView.setTypeface(fuente);
mBtnRecuperar = (Button) findViewById(R.id.btnRecuperar);
mBtnRecuperar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RecuperarContrasenia.class);
startActivity(intent);
}
});
mBtnRegistrar = (Button) findViewById(R.id.btnRegistrar);
mBtnRegistrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RegistrarUsuario.class);
startActivity(intent);
}
});
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
String userDetails = preference.getString(username + password + "data","No information on that user.");
SharedPreferences.Editor editor = preference.edit();
editor.putString("display",userDetails);
editor.commit();
if(mUsername.getText().toString().trim().length() == 0 && mPassword.getText().toString().trim().length() == 0 ){
Toast.makeText(MainActivity.this, "Los campos estan vacios", Toast.LENGTH_SHORT).show();
}else
{
if(mUsername.getText().toString().trim().equals(username) && mPassword.getText().toString().trim().equals(password)){
Toast.makeText(MainActivity.this, "Bienvenido", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this,PantallaPrincipal.class);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Los campos son incorrectos", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
i dont know what im missing that it dont verify the user if exists or login with the credentials i make in RegisterActivity.class
thanks
You are never retrieving the username and password from SharedPreferences. And at the end you are checking the information the user puts in the TextEdits against itself so the validation always returns true to any non empty value.
Change this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
To this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = preference.getString("Username", "");
String password = preference.getString("Password", "");

SharedPreferences to save login data

In my application a user starts the application and try to logs in , the application checks whether there is in the Shared Set < User> with the list of credentials for all users , if it does not exist create it from scratch .... Here's my question is how do I check in the shared existence of this Set < User>?
Here, have a look at my code for shared preferences. This code will save your login data.
public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String e = email.getText().toString();
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.commit();
}
public void clear(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
name.setText("");
email.setText("");
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here is simple login code we can store data by putString method of Editor class
SharedPreferences.Editor editor = sp.edit();
editor.putString("User", c.getString(c.getColumnIndex("Name")).toString());
editor.commit();
full code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
btn = (Button) findViewById(R.id.button);
btn3 = (Button) findViewById(R.id.button3);
btn3 = (Button) findViewById(R.id.button3);
ct = (Button) findViewById(R.id.ct);
final SQLiteDatabase db = openOrCreateDatabase("DemoDb",MODE_ENABLE_WRITE_AHEAD_LOGGING,null);
ct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.execSQL("create table login(LoginId varchar(10) primary key,Password varchar(10),Name varchar(10));");
}
});
sp = getSharedPreferences("myLogin", MODE_PRIVATE);
if(!sp.getBoolean("LogInMode",false)) {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( et1.getText().toString().length()==0 || et2.getText().toString().length()==0){
Toast.makeText(getBaseContext(), "User Not Found", Toast.LENGTH_SHORT).show();
}else {
String data = "content://com.example.maity.dbdemo.123/DemoDb";
Uri uri = Uri.parse(data);
ContentResolver resolver = getContentResolver();
String[] ar = {"", ""};
ar[0] = et1.getText().toString().trim();
ar[1] = et2.getText().toString().trim();
final Cursor c = resolver.query(uri, null, null, ar, null);
if (c.moveToNext()) {
if ((et1.getText().toString().trim().equals(c.getString(c.getColumnIndex("LoginId")).toString())) &&
(et2.getText().toString().trim().equals(c.getString(c.getColumnIndex("Password")).toString()))) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("LogInMode", true);
editor.putString("User", c.getString(c.getColumnIndex("Name")).toString());
editor.commit();
Intent intent = new Intent(MainActivity.this, WelcomePage.class);
startActivity(intent);
finish();
}
}else {
Toast.makeText(getBaseContext(), "User Not Found", Toast.LENGTH_SHORT).show();
}
}
}
});
}
else{
Intent intent = new Intent(MainActivity.this, WelcomePage.class);
startActivity(intent);
finish();
}
}
If your login api response is like below
{
"status": true,
"message": "Login Success",
"data": {
"user_id": "1",
"first_name": "Ketan",
"last_name": "Ramani",
"username": "ketanramani"
}
}
Then you can save all login response by dynamically using below code
SharedPreferences preferences = getApplicationContext().getSharedPreferences("LoginPref", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(dataObject.toString());
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
editor.putString(key, jsonObject.optString(key)).apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
Your data will save in sharedpreferences like below
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="user_id">1</string>
<string name="first_name">Ketan</string>
<string name="last_name">Ramani</string>
<string name="username">ketanramani</string>
</map>

Sharing the SharedPreferences

I have 2 activities namely MainActivity and OKActivity. The MainActivity statically checks for a password and lets you go to the OKActivity. I have used SharedPrefrences in the OKActivity for changing the password to a new one.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText password = (EditText) findViewById(R.id.editText_Password);
Button enter = (Button) findViewById(R.id.button);
enter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String user_pass;
user_pass = password.getText().toString();
if (user_pass.isEmpty()) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
dialogBuilder.setIcon(R.drawable.ic_launcher);
dialogBuilder.setTitle("Oops!");
dialogBuilder.setMessage("Password Field Cannot Be Empty");
dialogBuilder.setPositiveButton("OK", null);
dialogBuilder.show();
}
else
if (user_pass.equals("123")) {
Toast.makeText(MainActivity.this, "Welcome!", Toast.LENGTH_SHORT).show();
Intent I = new Intent("com.mavenmaverick.password.OKActivity");
startActivity(I);
}
else
if(user_pass != ("123")){
Toast.makeText(MainActivity.this, "Incorrect", Toast.LENGTH_SHORT).show();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
dialogBuilder.setIcon(R.drawable.ic_launcher);
dialogBuilder.setTitle("Oops!");
dialogBuilder.setMessage("Incorrect Password");
dialogBuilder.setPositiveButton("OK", null);
dialogBuilder.show();
}
}
});
}
public class OKActivity extends Activity {
EditText newPassword;
String newUserPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ok);
newPassword = (EditText) findViewById(R.id.new_password);
newUserPassword = newPassword.getText().toString();
getpasswordSharedPreferences();
Button changePassword = (Button) findViewById(R.id.button_change);
changePassword.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
newUserPassword = newPassword.getText().toString();
getpasswordSharedPreferences();
setSharedPreferences();
}
});
}
private String getpasswordSharedPreferences() {
SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
String password = userPassword.getString("THE_PASSWORD", "123");
return password;
}
private void setSharedPreferences() {
SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
SharedPreferences.Editor password_edior = userPassword.edit();
password_edior.putString("THE_PASSWORD", newUserPassword);
password_edior.commit();
Toast.makeText(OKActivity.this, "Password Change Succesful", Toast.LENGTH_SHORT).show();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(OKActivity.this);
dialogBuilder.setIcon(R.drawable.ic_launcher);
dialogBuilder.setTitle("Done!");
dialogBuilder.setMessage("New Password : "+newUserPassword);
dialogBuilder.setPositiveButton("OK", null);
dialogBuilder.show();
}
How can I access the SharedPrefrences in OKActivity for the password and use it in my MainActivity to allow access thereby making things dynamic over user-interaction cycles.
Just access the SharedPreferences in your OKActivity and in your MainActivity. The trick is to use the same TAG name - in your case it's 'USER_PASSWORD'.
Have a look at this --> SharedPreferences
Create a SharedPrefrences.java //then we can use when ever we need
public class SharedPrefrences {
public static void saveData(String name, String value, Context context) {
try {
SharedPreferences settings = context
.getSharedPreferences(Configuration.getPrefsName(), 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(name, value);
editor.commit();
} catch (NullPointerException ignored) {
}
}
public static String getData(String name, Context context) {
try {
SharedPreferences settings = context
.getSharedPreferences(Configuration.getPrefsName(), 0);
return settings.getString(name, "");
} catch (NullPointerException ignored) {
return "";
}
}
}
//In MainActivity
SharedPrefrences.saveData("Password","123456", getApplicationContext());
//In OKActivity
String passwordfromMainActivty = PreferencesUtils.getData("Password", getApplicationContext());
//To Add Newpassword
SharedPrefrences.saveData("NewPassword","abcd", getApplicationContext());
You get the same way in both activity's. Do get of your SharedPreferences with the same TAG.
private String getpasswordSharedPreferences() {
SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
String password = userPassword.getString("THE_PASSWORD", "123");
return password;
}
Maybe you can put this method's in other class, and call when you want from all activities:
You can put your set method here too
For example:
public class SharedPrefs {
private static final String SHARED_PREF = "USER_PASSWORD";
private static final String KEY_PASSWORD = "THE_PASSWORD";
public static void getStoredSharedPref(Context context, String key, String value) {
SharedPreferences sharedPref = context.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(propertyKey, value);
editor.commit();
}
}
and then call in your activities
SharedPrefs.getStoredSharedPref(context, SharedPrefsUtils.KEY_PASSWORD,"1234");

Email id and phone number not validating

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;
}
}

Categories

Resources