How to implement Password Validation with password patterns in Android? - java

I want to add a Password Validation on this, but getting problem in getting it, I want a password pattern which includes at least some of these:
number of characters
special characters
lowercase letters
uppercase letters
But I am unable to achieve this, please help.
I am using Android Studio, below is my Java class file:
public class SignUp extends MainActivity {
private EditText et_name, et_email, et_password, et_cpassword;
private String name, email, password, cpassword;
Button signupbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up_form);
et_name = (EditText) findViewById(R.id.name);
et_email = (EditText) findViewById(R.id.Email);
et_password = (EditText) findViewById(R.id.Password);
et_cpassword = (EditText) findViewById(R.id.Confirm_Password);
signupbtn = (Button) findViewById(R.id.Signbtn);
signupbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register();
}
});
}
public void register() {
initialise();
if (!validate()) {
Toast.makeText(this, "Sign up Failed", Toast.LENGTH_SHORT).show();
} else {
onSignUpSuccess();
}
}
public void onSignUpSuccess() {
Intent intent = new Intent(SignUp.this, HomePage.class);
startActivity(intent);
finish();
}
public boolean validate() {
boolean valid = true;
if (name.isEmpty() || name.length() > 32) {
et_name.setError("please enter valid name");
valid = false;
}
if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
et_email.setError("please enter valid Email");
valid = false;
}
if (password.isEmpty() )
et_password.setError("please enter a valid password");
return valid;
}
public void initialise(){
name = et_name.getText().toString().trim();
email = et_email.getText().toString().trim();
password = et_password.getText().toString().trim();
cpassword = et_cpassword.getText().toString().trim();
}
}

The pattern that you are looking for looks like this:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$
This is a complete pattern that should force the user to use digits, lower case, upper case and special characters.

You can use this following class.
public class Validation {
// Regular Expression
// you can change the expression based on your need
private static final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
//private static final String EMAIL_REGEX = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
private static final String PHONE_REGEX = "\\d{3}-\\d{7}";
private static final String ZIP_REGEX = "\\d{5}";
// Error Messages
private static final String REQUIRED_MSG = "required";
private static final String EMAIL_MSG = "invalid email";
private static final String PHONE_MSG = "###-#######";
private static final String ZIP_MSG = "#####";
public static boolean isEmailAddress(EditText editText, boolean required) {
return isValid(editText, EMAIL_REGEX, EMAIL_MSG, required);
}
public static boolean isPhoneNumber(EditText editText, boolean required) {
return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}
public static boolean isZip(EditText editText,boolean required){
return isValid(editText,ZIP_REGEX,ZIP_MSG,required);
}
public static boolean isValid(EditText editText, String regex, String errMsg, boolean required) {
String text = editText.getText().toString().trim();
editText.setError(null);
if ( required && !hasText(editText) ) return false;
if (required && !Pattern.matches(regex, text)) {
editText.setError(errMsg);
return false;
};
return true;
}
public static boolean hasText(EditText editText) {
String text = editText.getText().toString().trim();
editText.setError(null);
if (text.length() == 0) {
editText.setError(REQUIRED_MSG);
return false;
}
return true;
}
}

Related

How can i change the value of a TextView Instantly, as i push the update button that retrieves data from a Database?

public class UserprofileActivity extends AppCompatActivity {
// VARIABLES
TextView fullName, userName, location, motorcycle;
TextInputLayout fullNameInput, emailInput, motorcycleInput, passwordInput;
// GLOBAL VARIABLES TO HOLD USER DATA INSIDE THIS ACTIVITY
String _NAME, _USERNAME, _EMAIL, _LOCATION, _MOTORCYCLE, _PASSWORD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userprofile);
reference = FirebaseDatabase.getInstance().getReference("users");
// HOOKS
fullName = findViewById(R.id.profileFullName);
userName = findViewById(R.id.profileUsername);
location = findViewById(R.id.profileLocalization);
motorcycle = findViewById(R.id.profileMotorcycle);
fullNameInput = findViewById(R.id.profile_FullName);
emailInput = findViewById(R.id.profile_Email);
motorcycleInput = findViewById(R.id.profile_Motorcycle);
passwordInput = findViewById(R.id.profile_Password);
// SHOW ALL DATA
showAllUserData();
}
private void showAllUserData() {
Intent intent = getIntent();
_NAME = intent.getStringExtra("name");
_USERNAME = intent.getStringExtra("username");
_EMAIL = intent.getStringExtra("email");
_LOCATION = intent.getStringExtra("location");
_MOTORCYCLE = intent.getStringExtra("motorcycle");
_PASSWORD = intent.getStringExtra("password");
// this variable goes to (TextInputLayout "fullNameInput) and (TextView fullName) this goes to update the full name of the user and also is motorcycle brand. It should update both TextViews(Full Name and Motorcycle) with the data retrieved from the database at the same time and as soon as i would click the update button below the form. But it only updates after a new login. (The table name of the Database is users and the first child is the Username). enter image description here
fullName.setText(_NAME);
userName.setText(_USERNAME);
location.setText(_LOCATION);
motorcycle.setText(_MOTORCYCLE);
Objects.requireNonNull(fullNameInput.getEditText()).setText(_NAME);
Objects.requireNonNull(emailInput.getEditText()).setText(_EMAIL);
Objects.requireNonNull(motorcycleInput.getEditText()).setText(_MOTORCYCLE);
Objects.requireNonNull(passwordInput.getEditText()).setText(_PASSWORD);
}
private boolean isNameChanged() {
if (!_NAME.equals(Objects.requireNonNull(fullNameInput.getEditText()).getText().toString())) {
reference.child(_USERNAME).child("name").setValue(fullNameInput.getEditText().getText().toString());
fullName.getText().equals(_NAME);
return true;
} else {
return false;
}
}
private boolean isMotorcycleChanged() {
if (!_MOTORCYCLE.equals(Objects.requireNonNull(motorcycleInput.getEditText()).getText().toString())) {
reference.child(_USERNAME).child("motorcycle").setValue(motorcycleInput.getEditText().getText().toString());
return true;
} else {
return false;
}
}
public void update(View view) {
if (isNameChanged() || isEmailChanged() || isMotorcycleChanged() || isPasswordChanged()) {
Toast.makeText(this, "Data has been Updated Successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Data is the Same and therefore Cannot be Updated", Toast.LENGTH_LONG).show();
}
}
}

Unable to use boolean values in IF statements

I have a database that is being checked using a Cursor. This database compares the data in the database to the user entered username and password. If they match data in the database a boolean is returned true. I can use a toast to output the boolean which correctly outputs as true or false if the input data does or does not match.
However, i am trying to use the boolean to move to the next activity. If the boolean is true the next intent is started. This does not work for some reason and I cant seem to work out why. Any help would be great. Thanks!
public Button btnLogin, btnSignup;
public EditText UsernameInput, PasswordInput;
public DatabaseHelper db;
public static String passUser, passPass, passFirst, passSecond;
public int count;
public Boolean matchingUser = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Align page and remove notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
// Define everything
btnLogin = findViewById(R.id.btnLogin);
btnSignup = findViewById(R.id.btnSignup);
UsernameInput = findViewById(R.id.UsernameInput);
PasswordInput = findViewById(R.id.PasswordInput);
db = new DatabaseHelper(this);
// validation button
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validateLogin(UsernameInput.getText().toString(), PasswordInput.getText().toString());
}
});
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateUser();
}
});
}
// Validation code
public void validateLogin(String userName, String userPassword)
{
if (userName.equals("")|| userPassword.equals(""))
{
Toast.makeText(getApplicationContext(),"Fields are empty",Toast.LENGTH_SHORT).show();
}
else
{
// CHECKING USER LOGIN DETAILS
Cursor cursor = db.CompareUserData();
for (count = 0; count<=cursor.getCount();count++)
{
if (cursor.moveToPosition(count))
{
if (UsernameInput.getText().toString().equals(cursor.getString(0))&&PasswordInput.getText().toString().equals(cursor.getString(1)))
{
matchingUser = true;
}
}
Toast.makeText(this, "boolean : "+ matchingUser, Toast.LENGTH_SHORT).show();
if (matchingUser = true)
{
passUser = cursor.getString(0);
passPass = cursor.getString(1);
passFirst = cursor.getString(2);
passSecond = cursor.getString(3);
getUser();
getPass();
getFirst();
getSecond();
Toast.makeText(getApplicationContext(), "Successfully logged in", Toast.LENGTH_SHORT).show();
LoginValidation();
}
if (matchingUser = false)
{
Toast.makeText(getApplicationContext(),"Incorrect Username",Toast.LENGTH_SHORT).show();
}}
}
}
private void LoginValidation()
{
// Changing activity code
startActivity(new Intent(MainActivity.this,Login_Biometrics.class));
}
private void CreateUser()
{
// Changing activity code
startActivity(new Intent(MainActivity.this,createUser.class));
}
public static String getUser ()
{
return passUser;
}
public static String getPass ()
{
return passPass;
}
public static String getFirst ()
{
return passFirst;
}
public static String getSecond ()
{
return passSecond;
}
It wont work with one = equal sign just do:
if(matchingUser) {
// if true do something
} else {
// if false do something
}
In your case:
if (matchingUser) {
passUser = cursor.getString(0);
passPass = cursor.getString(1);
passFirst = cursor.getString(2);
passSecond = cursor.getString(3);
getUser();
getPass();
getFirst();
getSecond();
Toast.makeText(getApplicationContext(), "Successfully logged in",Toast.LENGTH_SHORT).show();
LoginValidation();
} else {
Toast.makeText(getApplicationContext(),"Incorrect Username",Toast.LENGTH_SHORT).show();
}
You have to understand some basics:
Assignment operator =
Is used to assign value to some variable.
Logical operator ==
Is used to make some logical comparison.
So instead of doing this:
if (matchingUser = true)
{
...
Do this
if (matchingUser == true)
{
...
Apply this for every condition checking in your code.

What is the proper way to load user data from database and pass it into intent extras

The project im working on allow the user to register and login and all works perfectly until I spotted something wrong with the code. It doesn't count as an error because the compiler don't think its an error. Its just a bug or whatever people call it is. So here's what happened . The user login to their account, the database transfer their data into intent extras. then on the next activities, the username, coins and gems appears on top of the page so that the user know how much coins they have left. For testing purpose, i added add coin and decrease coin button. still, the code works perfectly. But after the user log out and relogin, the coins backs to the original amount. I know the problem caused by putting a value on the coin variable in User.java class. And still while logging in I put the default value of coins and gems for the user in the intent extras. I just cant find my way on how to put the value from database to the intent extras while user logging in.
so heres the code for login activity
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Check user input is correct or not
if (validate()) {
//Get values from EditText fields
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
User player1 = new User(null, null, Email, Password);
//Authenticate user
User currentUser = myDb.Authenticate(player1);
//Check Authentication is successful or not
if (currentUser != null) {
System.out.println("Success");
Bundle extras = new Bundle();
extras.putString("P_ID", currentUser.getId());
extras.putString("P_NAME", currentUser.getName());
extras.putInt("P_COINS", currentUser.getCoins());
extras.putInt("P_GEMS", currentUser.getGems());
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
intent.putExtras(extras);
startActivity(intent);
finish();
} else {
//User Logged in Failed
System.out.println("Failed");
}
}
}
});
the homeactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set fullscreen and no title//////////
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
///////////////////////////////////////
setContentView(R.layout.home_screen);
myDb = new DatabaseHelper(this);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
pid = extras.getString("P_ID");
pname = extras.getString("P_NAME");
pcoins = extras.getInt("P_COINS");
pgems = extras.getInt("P_GEMS");
nametxt = (TextView)findViewById(R.id.playernametext);
coinstxt = (TextView)findViewById(R.id.playercoinstext);
gemstxt = (TextView)findViewById(R.id.playergemstext);
addcoin = (Button)findViewById(R.id.addbtn);
decoin = (Button)findViewById(R.id.decbtn);
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
addcoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pcoins += 10;
boolean isUpdate = myDb.updateUser(pid, pname, String.valueOf(pcoins), String.valueOf(pgems));
if (isUpdate == true) {
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
}
}
});
decoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pcoins -= 10;
boolean isUpdate = myDb.updateUser(pid, pname, String.valueOf(pcoins), String.valueOf(pgems));
if (isUpdate == true) {
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
}
}
});
}
and of course the user class
public class User {
public String id;
public String userName;
public String email;
public String password;
public int coins = 1000;
public int gems = 10;
public User(String id, String userName, String email, String password) {
this.id = id;
this.userName = userName;
this.email = email;
this.password = password;
}
public String getId() {
return this.id;
}
public String getName() {
return this.userName;
}
public void addCoins(int addAmount) {
this.coins = addAmount;
}
public void decCoins(int decAmount) {
this.coins = decAmount;
}
public int getCoins() {
return this.coins;
}
public void addGems(int addAmount) {
this.gems = addAmount;
}
public void decGems(int decAmount) {
this.gems = decAmount;
}
public int getGems() {
return this.gems;
}
}
Honestly, my brain lacks of logic. Thats why i come here, to see whether my code does make sense.
And please, if you don't understand what i mean, just ask me which parts and please just dont immediately flag my question. Im really bad at english, trust me.
I'd suggest only passing the userid (which should never change) and then always getting the values coins etc from the database and also only changing them in the database (followed by resetting the displayed values from the values in the database).
You would then not have the issue of trying to juggle two sets of data you would then rely on the real data i.e. that in the database.
Working Example
The following is some code that goes through the basics.
When it starts the MainActivity, immediately starts the LoginActivity when you login then it takes you to the HomeActivity. This display the current Userid, Username, coins (initially 0) and gems.
There are 2 buttons Add10Coins and Add10gems clicking them will apply the new values to the DB displaying the updated values. If you stop the App and rerun, login then the values will be as they were.
Passing values wise, although the LoginActivity sets 3 Intent Extra values only one is used (the userid as a long) by the HomeActivity, but as per the values display all are accessible. If another activity is started then all you have to do is pass the userid via the intent.
The code isn't what I'd call complex but I'd certainly suggest going through it and try to understand it.
user.java
I've added some methods and also added some Constants, this is now :-
public class User {
public static final int ADJUSTTYPE_ADD = 1;
public static final int ADJUSTTYPE_REPLACE = 2;
public static final int ADJUSTTYPE_MULTIPLY = 3;
public static final int ADJUSTTYPE_DIVIDE = 4;
String id;
String userName;
String email;
String password;
int coins;
int gems;
public User(String id, String userName, String email, String password) {
this.id = id;
this.email = email;
//And so on. Don't mind this
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setName(String userName) {
this.userName = userName;
}
public String getName() {
return this.userName;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setCoins(int coins) {
this.coins = coins;
}
public int getCoins() {
return this.coins;
}
public void setGems(int gems) {
this.gems = gems;
}
public int getGems() {
return this.gems;
}
public long getLongId() {
long id;
try {
id = Long.valueOf(this.id);
} catch (Exception e) {
return -1;
}
return id;
}
}
DatabaseHelper.java
This has been written from scratch based upon not the most stringent inspection of your code, it will largely be affected by my styling/usage techniques but not to the extent that I'd apply for real development.
Within this is the method adjustCoinsAndOrGems this is what is used to update the gems or coins in the DB and also in the returned User (so that a synchronised version of the User is returned, not that this returned use is used (I personally prefer to access the database as long as it's not an issue (e.g. noticeably affects performance)))
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mygame.db";
public static final int DBVERSION = 1;
public static final String TBL_USER = "user";
public static final String COL_USER_ID = BaseColumns._ID;
public static final String COL_USER_NAME = "user_name";
public static final String COL_USER_EMAIL = "user_email";
public static final String COL_USER_PASWWORD = "user_password";
public static final String COL_USER_COINS = "user_coins";
public static final String COL_USER_GEMS = "user_gems";
public static final String TBL_PLAYER = "player";
public static final String COL_PLYAER_ID = BaseColumns._ID;
public static final String COL_PLAYER_OWNINGUSER = "player_owninguser";
public static final String COL_PLAYER_NAME = "player_name";
//...... other columns
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_tbl_user = "CREATE TABLE IF NOT EXISTS " + TBL_USER + "(" +
COL_USER_ID + " INTEGER PRIMARY KEY," +
COL_USER_NAME + " TEXT NOT NULL UNIQUE," +
COL_USER_EMAIL + " TEXT NOT NULL UNIQUE," +
COL_USER_PASWWORD + " TEXT NOT NULL," +
COL_USER_COINS + " INTEGER," +
COL_USER_GEMS + " INTEGER" +
")";
String crt_tbl_player = "CREATE TABLE IF NOT EXISTS " + TBL_PLAYER + "(" +
COL_PLYAER_ID + " INTEGER PRIMARY KEY," +
COL_PLAYER_NAME + " TEXT NOT NULL," +
COL_PLAYER_OWNINGUSER + " INTEGER REFERENCES " + TBL_USER + "(" + COL_USER_ID + ")" +
")";
db.execSQL(crt_tbl_user);
db.execSQL(crt_tbl_player);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
/*
Note core add but not intended to be used directly
Note this assumes that checks are done to ensure that name, email and password
have been provided
*/
private long addUser(Long id, String name, String email, String password, int coins, int gems) {
ContentValues cv = new ContentValues();
if (id > 0) {
cv.put(COL_USER_ID,id);
}
if (name.length() > 0) {
cv.put(COL_USER_NAME,name);
}
if (email.length() > 0 ) {
cv.put(COL_USER_EMAIL,email);
}
if (password.length() > 0) {
cv.put(COL_USER_PASWWORD,password);
}
cv.put(COL_USER_COINS,coins);
cv.put(COL_USER_GEMS,gems);
if (cv.size() < 1) return -1; //<<<<<<<<<< return if nothing to add
return mDB.insert(TBL_USER,null,cv);
}
/*
For add with just name, email and password (normal usage)
*/
public long addUser(String name, String email, String password) {
return this.addUser(-1L,name,email,password,0,0);
}
/*
For adding a user setting the coins and gems (special usage)
*/
public long addUserSettingCoinsAndGems(String name, String email, String password, int coins, int gems) {
return this.addUser(-1L,name,email,password,coins,gems);
}
public User getUser(long id) {
User rv = new User("-1","",",",""); // Invalid user
String whereclause = COL_USER_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId(String.valueOf(id));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User getUser(String userid) {
String whereclause = COL_USER_ID + "=?";
User rv = new User("-1","",",",""); // Invalid user
long id;
try {
id = Long.valueOf(userid);
} catch (Exception e) {
return rv;
}
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId(String.valueOf(id));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User getUser(String email, String password) {
User rv = new User("-1","","","");
String whereclause = COL_USER_EMAIL + "=? AND " + COL_USER_PASWWORD + "=?";
String[] whereargs = new String[]{email,password};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId( String.valueOf(csr.getLong(csr.getColumnIndex(COL_USER_ID))));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User adjustCoinsAndOrGems(User u, int coins, int coin_adjustmode, int gems, int gem_adjustmode) {
ContentValues cv = new ContentValues();
User rv;
User user_fromDB = getUser(u.getId());
if (user_fromDB.id.equals("-1")) return u; // User not found so return
switch (coin_adjustmode) {
case User.ADJUSTTYPE_REPLACE:
cv.put(COL_USER_COINS,coins);
break;
case User.ADJUSTTYPE_ADD:
if (coins != 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() + coins);
}
break;
case User.ADJUSTTYPE_MULTIPLY:
if (coins > 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() * coins);
}
break;
case User.ADJUSTTYPE_DIVIDE:
if (coins > 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() / coins);
}
break;
}
switch (gem_adjustmode) {
case User.ADJUSTTYPE_REPLACE:
cv.put(COL_USER_GEMS,gems);
break;
case User.ADJUSTTYPE_ADD:
if (gems != 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() + gems);
}
break;
case User.ADJUSTTYPE_MULTIPLY:
if (gems > 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() * gems);
}
break;
case User.ADJUSTTYPE_DIVIDE:
if (gems > 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() / gems);
}
break;
}
if (cv.size() < 1) return u;
String whereclause = COL_USER_ID + "=?";
String[] whereargs = new String[]{u.getId()};
mDB.update(TBL_USER,cv,whereclause,whereargs);
return getUser(user_fromDB.getId());
}
public boolean authenticateUser(String email, String password) {
User u = getUser(email,password);
return (u.getLongId() > 0);
}
}
MainActivity.java
Very simple activity that starts the LoginActivity and when finally returned to does nothing (so you might as well kill the app).
public class MainActivity extends AppCompatActivity {
TextView mMessage;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessage = this.findViewById(R.id.message);
mDB = new DatabaseHelper(this);
addSomeTestingUsers();
// Immediately start Login Activity
Intent i = new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
#Override
protected void onResume() {
super.onResume();
mMessage.setText("Welcome back");
}
private void addSomeTestingUsers() {
if (DatabaseUtils.queryNumEntries(mDB.getWritableDatabase(),DatabaseHelper.TBL_USER) > 0) return;
mDB.addUser("Fred","fred#fredmal.com","password");
mDB.addUser("Mary","mary#mary.email.com","password");
}
}
LoginActivity
This is pretty straightforward note that as it stands you have to Login and that the emails and passwords for the 2 users are coded in the MainActivity. When supplied correctly the HomeActivivty is started :-
public class LoginActivity extends AppCompatActivity {
public static final String INTENTKEY_USERNAME = "IK_USERNAME";
public static final String INTENTKEY_USERID = "IK_USERID";
public static final String INTENTKEY_STRINGUSERID = "IK_USERIDSTRING";
Button mloginbtn;
EditText mEmail,mPassword;
Context mContext;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
mloginbtn = this.findViewById(R.id.loginbtn);
mEmail = this.findViewById(R.id.email);
mPassword = this.findViewById(R.id.password);
mDB = new DatabaseHelper(this);
mloginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
handleAuthentication();
}
});
}
private void handleAuthentication() {
if (mDB.authenticateUser(mEmail.getText().toString(),mPassword.getText().toString())) {
User u = mDB.getUser(mEmail.getText().toString(),mPassword.getText().toString());
Intent i = new Intent(mContext,HomeActivity.class);
i.putExtra(INTENTKEY_USERNAME,u.getName());
i.putExtra(INTENTKEY_USERID,u.getLongId());
i.putExtra(INTENTKEY_STRINGUSERID,u.getId());
startActivity(i);
finish();
}
}
HomeActivity
For brevity, this has been used to display the coins and gems, it to is pretty basic and relies upon methods in the DatabaseHelper to do much of the work.
public class HomeActivity extends AppCompatActivity {
TextView mUserameTextView, mUseridTextView, mCoinsTextView, mGemsTextView;
Button mAdd10Coins, mAdd10Gems,mDone;
User mUser;
long mUserid;
Context mContext;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mContext = this;
mDB = new DatabaseHelper(mContext);
mUserameTextView = this.findViewById(R.id.username);
mUseridTextView = this.findViewById(R.id.userid);
mCoinsTextView = this.findViewById(R.id.coins);
mGemsTextView = this.findViewById(R.id.gems);
Intent i = this.getIntent();
mUserid = i.getLongExtra(LoginActivity.INTENTKEY_USERID,-1);
mUser = mDB.getUser(mUserid);
refreshDisplay();
initButtons();
}
private void initButtons() {
mAdd10Coins = this.findViewById(R.id.add10coins);
mAdd10Coins.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDB.adjustCoinsAndOrGems(mUser,10,User.ADJUSTTYPE_ADD,0,User.ADJUSTTYPE_ADD);
mUser = mDB.getUser(mUserid);
refreshDisplay();
}
});
mAdd10Gems = this.findViewById(R.id.add10gems);
mAdd10Gems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDB.adjustCoinsAndOrGems(mUser,0, User.ADJUSTTYPE_ADD,10,User.ADJUSTTYPE_ADD);
mUser = mDB.getUser(mUserid);
refreshDisplay();
}
});
mDone = this.findViewById(R.id.done);
mDB = new DatabaseHelper(mContext);
mDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
private void refreshDisplay() {
mUseridTextView.setText(mUser.getId());
mUserameTextView.setText(mUser.getName());
mCoinsTextView.setText(String.valueOf(mUser.getCoins()));
mGemsTextView.setText(String.valueOf(mUser.getGems()));
}
}

Java - Checking if int is empty

I'm trying to do field validation for an int in android studio. The code for the field is as follows;
public class Register extends ActionBarActivity implements View.OnClickListener {
EditText etName, etAge, etUsername, etPassword;
Button bRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bRegister:
String name = etName.getText().toString();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String ageText = etAge.getText().toString();
if(! TextUtils.isEmpty(ageText)) {
int age = Integer.parseInt(ageText);
}
if(name.length()==0)
{
etName.requestFocus();
etName.setError("Please don't leave the name field empty.");
}else if(username.length()==0)
{
etUsername.requestFocus();
etUsername.setError("Please don't leave the username field empty.");
}else if(password.length()==0)
{
etPassword.requestFocus();
etPassword.setError("Please don't leave the password field empty.");
}/*else if(age == null)
{
etAge.requestFocus();
etAge.setError("Please don't leave the age field empty.");
}*/
else if(!name.matches("[a-zA-Z]"))
{
etName.requestFocus();
etName.setError("Please only use alphabetic characters");
}else{
User user = new User(name, age, username, password);
registerUser(user);
}
break;
}
}
private void registerUser(User user) {
ServerRequest serverRequest = new ServerRequest(this);
serverRequest.storeUserDataInBackground(user, new GetUserCallback() {
#Override
public void done(User returnedUser) {
Intent loginIntent = new Intent(Register.this, Login.class);
startActivity(loginIntent);
}
});
}
}
But I can't get the int age validated, it keps giving me this error;
java.lang.NumberFormatException: Invalid int: ""
User class
public class User {
String name, username, password;
int age;
public User(String name, int age, String username, String password) {
this.name = name;
this.age = age;
this.username = username;
this.password = password;
}
Try this:
String ageText = etAge.getText().toString();
int age = 0;
if(! TextUtils.isEmpty(ageText)) // If EditText is not empty
age = Integer.parseInt(ageText); // parse its content to integer
// Continue validation...
instead of
int age = Integer.parseInt(etAge.getText().toString());
I believe you are looking for something like this:
String ageString = "25"; //age will be null if it is empty or not a number
Integer age = null;
try {
age = Integer.parseInt(ageString);
} catch (NumberFormatException e) {}
if (age == null) {
//enter age
}

Android Shared Preferences using getter/setter methods fail to display

My Android app fails to display the shared preferences that I set in a different class.
Am I missing something in my code? I save them fine but they don't display in my main Activity. All I see is the default text when I run the app. I have tried all I can to no avail. I can't figure out where the problem is. Below are my code files:
1. MnsEditor.java
public class MnsEditor extends Activity {
private MsItem mnses;
private Button saveBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mns_editor);
Intent intent = this.getIntent();
mnses = new MsItem();
mnses.setStartKey(intent.getStringExtra("startKey"));
mnses.setStartDate(intent.getStringExtra("StartDate"));
mnses.setShiftKey(intent.getStringExtra("ShiftKey"));
mnses.setShift(intent.getStringExtra("Shift"));
mnses.setBKey(intent.getStringExtra("BKey"));
mnses.setB(intent.getStringExtra("B"));
mnses.setGKey(intent.getStringExtra("GKey"));
mnses.setG(intent.getStringExtra("G"));
mnses.setNxtKey(intent.getStringExtra("NxtKey"));
mnses.setNxt(intent.getStringExtra("Nxt"));
EditText ms = (EditText) findViewById(R.id.sdate);
ms.setText(mnses.getStartDate());
EditText sh = (EditText) findViewById(R.id.sDay);
sh.setText(mnses.getShift());
EditText bb = (EditText) findViewById(R.id.bB);
bb.setText(mnses.getB());
EditText bg = (EditText) findViewById(R.id.bG);
bg.setText(mnses.getG());
EditText nm = (EditText) findViewById(R.id.Nxt);
nm.setText(mnses.getNxt());
saveBtn = (Button) findViewById(R.id.savePrefs);
saveBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
saveAndFinish();
}
});
}
private void saveAndFinish() {
EditText mst = (EditText) findViewById(R.id.stDay);
String mnsesStart = mst.getText().toString();
EditText shi = (EditText) findViewById(R.id.ShiftDay);
String shift = shi.getText().toString();
EditText bb = (EditText) findViewById(R.id.bbB);
String bbb = b.getText().toString();
EditText gg = (EditText) findViewById(R.id.ggG);
String ggg = gg.getText().toString();
EditText nxt = (EditText) findViewById(R.id.Nxt);
String next = nxt.getText().toString();
Intent intent = new Intent();
intent.putExtra("startdatekey", mnses.getStartDate());
intent.putExtra("StartDate", mnsesStart);
intent.putExtra("ShiftKey", mnses.getShift());
intent.putExtra("Shift", shift);
intent.putExtra("BKey", mnses.getB());
intent.putExtra("B", bbb);
intent.putExtra("GKey", mnses.getG());
intent.putExtra("G", ggg);
intent.putExtra("NxtKey", mnses.getNxt());
intent.putExtra("Nxt", next);
setResult(RESULT_OK, intent);
finish();
}
}
2. MsDataSource.java
public class MsDataSource {
MsItem mnses;
private static final String MNS_PREFS = "mnsKEY";
public SharedPreferences mnsPrefs;
public static final String StartDate = "startKey";
public static final String Shift = "shiftKey";
public static final String B = "bKey";
public static final String G = "gKey";
public static final String Nxt = "nxtKey";
public MsDataSource(Context context) {
mnsPrefs = context.getSharedPreferences(MNS_PREFS, Context.MODE_PRIVATE);
}
public String getTheStartDate() {
String mnsstart = mensPrefs.getString(StartDate, "Not seen");
return mnsstart;
}
public String getTheShift() {
String shiftda = mensPrefs.getString(Ovulation, "no data");
return shiftda;
}
public String getTheBoy() {
String Bda = mensPrefs.getString(B, "not accessible");
return Bda;
}
public String getTheGirl() {
String Gda = mensPrefs.getString(G, "does not exist");
return Gda;
}
public String getTheNextMenses() {
String nxtmns = mensPrefs.getString(Nxt, "maybe later");
return nxtmns;
}
public boolean update(mnsesItem mns) {
SharedPreferences.Editor editor = mnsPrefs.edit();
editor.putString(mns.getStartKey(), mns.getStartDate());
editor.putString(mns.getShiftKey(), mns.getShift());
editor.putString(mns.getBKey(), mns.getB());
editor.putString(mns.getGKey(), mns.getG());
editor.putString(mns.getNxtKey(), mns.getNxt());
editor.commit();
return true;
}
}
3. Mst.java
public class Mst extends Activity {
private TextView startdate;
private TextView shiftday;
private TextView bday;
private TextView gday;
private TextView nextday;
public static final String StartDate = "startKey";
public static final String Shift = "shiftKey";
public static final String B = "bKey";
public static final String G = "gKey";
public static final String Nxt = "nxtKey";
private static final int EDITOR_ACTIVITY_REQUEST = 1001;
private MsDataSource datasource;
MsItem mnses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mns_layout);
startdate = (TextView) findViewById(R.id.mnsstartd);
shiftday = (TextView) findViewById(R.id.shd);
bday = (TextView) findViewById(R.id.bbd);
gday = (TextView) findViewById(R.id.bgd);
nextday = (TextView) findViewById(R.id.nxtmnsd);
datasource = new MsDataSource(this);
refreshDisplay();
}
private void refreshDisplay() {
mnses = datasource.findAll();
startdate.setText(datasource.mnsPrefs.getString(StartDate, "not retrieved"));
shiftday.setText(datasource.mnsPrefs.getString(Shift, "unavailable"));
bday.setText(datasource.mnsPrefs.getString(B, "not seen"));
gday.setText(datasource.mnsPrefs.getString(G, "not found"));
nextday.setText(datasource.mnsPrefs.getString(Nxt, "no data"));
}
private void createMns() {
MsItem mns = MsItem.getNew();
Intent intent = new Intent(this, MnsEditor.class);
intent.putExtra("startKey", mns.getStartKey());
intent.putExtra("StartDate", mns.getStartDate());
intent.putExtra("shiftKey", mns.getShiftKey());
intent.putExtra("Shift", mns.getShift());
intent.putExtra("bKey", mns.getBKey());
intent.putExtra("B", mns.getB());
intent.putExtra("gKey", mns.getGKey());
intent.putExtra("G", mns.getG());
intent.putExtra("nxtKey", mns.getNxtKey());
intent.putExtra("Nxt", mns.getNxt());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDITOR_ACTIVITY_REQUEST && resultCode == RESULT_OK) {
MsItem mns = new MsItem();
mns.setStartKey(data.getStringExtra("startKey"));
mns.setStartDate(data.getStringExtra("StartDate"));
mns.setShiftKey(data.getStringExtra("shiftKey"));
mns.setShift(data.getStringExtra("Shift"));
mns.setBKey(data.getStringExtra("bKey"));
mns.setB(data.getStringExtra("B"));
mns.setGKey(data.getStringExtra("gKey"));
mns.setG(data.getStringExtra("G"));
mns.setNextmnsesKey(data.getStringExtra("nxtKey"));
mns.setNxt(data.getStringExtra("Nxt"));
datasource.update(mns);
refreshDisplay();
}
}
}
4. MsItem.java
#SuppressLint("SimpleDateFormat")
public class MsItem {
private String startKey;
private String StartDate;
private String shiftKey;
private String Shift;
private String bKey;
private String B;
private String gKey;
private String G;
private String nxtKey;
private String Nxt;
public String getStartKey() {
return startKey;
}
public void setStartKey(String startKey) {
this.startKey = startKey;
}
public String getStartDate() {
return StartDate;
}
public void setStartDate(String startDate) {
StartDate = startDate;
}
public String getShiftKey() {
return shiftKey;
}
public void setShiftKey(String shiftKey) {
this.shiftKey = shiftKey;
}
public String getShift() {
return Shift;
}
public void setShift(String shift) {
Shift = shift;
}
public String getbKey() {
return bKey;
}
public void setbKey(String bKey) {
this.bKey = bKey;
}
public String getB() {
return B;
}
public void setB(String b) {
B = b;
}
public String getgKey() {
return gKey;
}
public void setgKey(String gKey) {
this.gKey = gKey;
}
public String getG() {
return G;
}
public void setG(String g) {
G = g;
}
public String getNxtKey() {
return nxtKey;
}
public void setNxtKey(String nxtKey) {
this.nxtKey = nxtKey;
}
public String getNxt() {
return Nxt;
}
public void setNxt(String nxt) {
Nxt = nxt;
}
public static MsItem getNew(){
Locale locale = new Locale("en_US");
Locale.setDefault(locale);
String pattern = "yyyy-MM-dd HH:mm:ss Z";
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
String startdatekey = formatter.format(new Date());
String skey = formatter.format(new Date());
String bkey = formatter.format(new Date());
String gkey = formatter.format(new Date());
String nkey = formatter.format(new Date());
MsItem mnses = new MsItem();
mnses.setStartKey(startdatekey);
mnses.setStartDate("");
mnses.setShiftKey(skey);
mnses.setShift("");
mnses.setbKey(bkey);
mnses.setB("");
mnses.setgKey(gkey);
mnses.setG("");
mnses.setNxtKey(nkey);
mnses.setNxt("");
return mnses;
}
}
Try this:
public String getStartDate(){
mnsPrefs = context.getSharedPreferences(StartDate, Context.MODE_PRIVATE);
String mnsstart = mnsPrefs.getString(StartDate, "");
return mnsstart;
}
public String getShift(){
mnsPrefs = context.getSharedPreferences(shift, Context.MODE_PRIVATE);
String shiftda = mnsPrefs.getString(Shift, "");
return shiftda;
}
its more readable
Use MODE_APPEND instead MODE_PRIVATE.
MODE_APPEND(File creation mode: for use with openFileOutput, if the file already exists then write data to the end of the existing file instead of erasing it).
SharedPreferences editor = context.getSharedPreferences(
"used_name", Context.MODE_APPEND);
editor.putString("username", value);
editor.commit();
One issue I can see is, that You are trying to get the sharedPreferences, but You are initializing the same object a few times inside Your MsDataSource.java class:
mnsPrefs = context.getSharedPreferences(StartDate, Context.MODE_PRIVATE);
mnsPrefs = context.getSharedPreferences(shift, Context.MODE_PRIVATE);
mnsPrefs = context.getSharedPreferences(B, Context.MODE_PRIVATE);
mnsPrefs = context.getSharedPreferences(G, Context.MODE_PRIVATE);
mnsPrefs = context.getSharedPreferences(Nxt, Context.MODE_PRIVATE);
So this will not work. For different sharedPref objects, You need to initialize them unique for example:
public SharedPreferences mnsPrefs1;
public SharedPreferences mnsPrefs2;
public SharedPreferences mnsPrefs3;
public SharedPreferences mnsPrefs4;
public SharedPreferences mnsPrefs5;
mnsPrefs1 = context.getSharedPreferences(StartDate, Context.MODE_PRIVATE);
mnsPrefs2 = context.getSharedPreferences(shift, Context.MODE_PRIVATE);
mnsPrefs3 = context.getSharedPreferences(B, Context.MODE_PRIVATE);
mnsPrefs4 = context.getSharedPreferences(G, Context.MODE_PRIVATE);
mnsPrefs5 = context.getSharedPreferences(Nxt, Context.MODE_PRIVATE);
but there must be more. I need to see Your code from MsItem.java class, I think, here You are saving the SharedPrefs, right?
EDIT
You don´t need to initialize so many SharedPreference objects, it´s enough to make only one and give it different keys for every value. For example:
private final String sharedPrefKey = "MY_KEY";
public MsDataSource(Context context) {
mnsPrefs = context.getSharedPreferences(sharedPrefKey, Context.MODE_PRIVATE);
}
and then update() method in MsDataSource.java should work. But by the way, I think Your initialization of Your MsItem in Your Mst.java class at onActivityResult is made in the wrong way, isn´t it? You wrote
MsItem mns = new MsItem();
But musn´t it be
MsItem mns = MsItem.getNew();
? Because with only new MsItem(), all the Strings and stuff are not initialized inside MsItem.

Categories