Java - Checking if int is empty - java

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
}

Related

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

Why the id is changing every time on the same phone ? Firebase database

enter image description hereFirst of all i want to say that my english isn't very good but i hope this is not a problem (i hope). So I wrote a code that "should" get user id from the user of my app but every time
firebase get other id on the same phone can someone help me with this problem ?
If you need more info, please write it in comments . Thank you in advance. Here my code .
EditText editTextName;
Button buttonAdd;
Spinner spinnerGenres;
DatabaseReference databaseArtists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_cent);
databaseArtists = FirebaseDatabase.getInstance().getReference("prousers");
editTextName = (EditText) findViewById(R.id.editTextName);
buttonAdd = (Button) findViewById(R.id.buttonAddArtist);
spinnerGenres = (Spinner) findViewById(R.id.spinnerGenres);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addArtist();
}
});
}
private void addArtist(){
String name = editTextName.getText().toString().trim();
String genre = spinnerGenres.getSelectedItem().toString();
if (!TextUtils.isEmpty(name)){
String id = databaseArtists.push().getKey();
Artist artist = new Artist(id, name, genre);
databaseArtists.child(id).setValue(artist);
Toast.makeText(this, "You are a pro user :D", Toast.LENGTH_LONG).show();
finish();
System.exit(0);
}else{
Toast.makeText(this, "Something's wrong", Toast.LENGTH_LONG).show();
}
}
}
and this one too
public Artist(){
}
public Artist(String artistId, String artistName, String artistGenre) {
this.artistId = artistId;
this.artistName = artistName;
this.artistGenre = artistGenre;
}
public String getArtistId() {
return artistId;
}
public String getArtistName() {
return artistName;
}
public String getArtistGenre() {
return artistGenre;
}
}

How to implement Password Validation with password patterns in Android?

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

Bundle.getString() doesn't seem to get the values

I want my MainActivity to get extras from two different activties and I figured the only way to differ from the two activties is to check the key of the Bundles but when i try to get the extras that they come from, they are all null.
Main Activity:
public class UserActivity extends AppCompatActivity {
public String token;
public String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
Intent intent = getIntent();
Bundle b = intent.getExtras();
if(b.containsKey("createBundle"))
{
token = b.getString("sessionID");
name = b.getString("nameID");
}
else if(b.containsKey("logInBundle"))
{
token = b.getString("loginToken");
name = b.getString("loginName");
}
TextView welcome = (TextView) findViewById(R.id.welcomeView);
welcome.setText("Hello, " + name);
}
Activity 1:
public class CreateUserActivity extends Activity {
EditText txtName, txtEmail, txtPassword;
AlertDialogManager alert = new AlertDialogManager();
private String token;
private SharedPreferenceManager sharedPreferenceManager;
public void setToken(String token) {
this.token = token;
}
public String getToken() {
return token;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_user_activity);
txtName = (EditText) findViewById(R.id.loginName);
txtEmail = (EditText) findViewById(R.id.loginEmail);
txtPassword = (EditText) findViewById(R.id.loginPassword);
sharedPreferenceManager = new SharedPreferenceManager();
}
public void checkCreateUser(View view) throws JSONException {
String name = txtName.getText().toString();
String email = txtEmail.getText().toString();
String password = txtPassword.getText().toString();
String tokenAgain = "";
CheckBox checkBox = (CheckBox) findViewById(R.id.login_remember_checkbox);
if (name.trim().length() > 0 && password.trim().length() > 0 && email.trim().length() > 0) {
JSONObject userObj = new JSONObject();
userObj.put("name", name);
userObj.put("email", email);
userObj.put("password", password);
String jsonDocument = userObj.toString();
PostUserTask put = new PostUserTask();
put.execute("http://api.evang.dk/v2/users", jsonDocument);
tokenAgain = getToken();
if (checkBox.isChecked()) {
sharedPreferenceManager.saveData(CreateUserActivity.this, "USERNAME", name);
sharedPreferenceManager.saveData(CreateUserActivity.this, "EMAIL", email);
sharedPreferenceManager.saveData(CreateUserActivity.this, "PASSWORD", password);
sharedPreferenceManager.saveData(CreateUserActivity.this, "TOKEN", tokenAgain);
} else {
sharedPreferenceManager.removeData(CreateUserActivity.this, "USERNAME");
sharedPreferenceManager.removeData(CreateUserActivity.this, "EMAIL");
sharedPreferenceManager.removeData(CreateUserActivity.this, "PASSWORD");
sharedPreferenceManager.removeData(CreateUserActivity.this, "TOKEN");
}
}
else
{
alert.showAlertDialog(CreateUserActivity.this, "Login failed!", "Please enter name, username and password", false);
}
Intent i = new Intent(getBaseContext(), UserActivity.class);
Bundle b = new Bundle();
b.putString("sessionID", tokenAgain);
b.putString("nameID", name);
i.putExtra("createBundle", b);
startActivity(i);
}
Activity 2:
public class LoginActivity extends AppCompatActivity {
EditText userNameTxt, passwordTxt, emailTxt;
SharedPreferenceManager sharedPreferenceManager;
String userName;
String token;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Intent intent = getIntent();
userNameTxt = (EditText) findViewById(R.id.userNameLogin);
passwordTxt = (EditText) findViewById(R.id.passwordLogin);
emailTxt = (EditText) findViewById(R.id.emailLogin);
sharedPreferenceManager = new SharedPreferenceManager();
userName = sharedPreferenceManager.getData(this, "USERNAME");
String email = sharedPreferenceManager.getData(this, "EMAIL");
String password = sharedPreferenceManager.getData(this, "PASSWORD");
token = sharedPreferenceManager.getData(this, "TOKEN");
if(userName != null && email != null && password != null && token != null)
{
userNameTxt.setText(userName);
emailTxt.setText(email);
passwordTxt.setText(password);
}
}
public void onClickLog(View view) {
if(token != null)
{
Intent i = new Intent(getBaseContext(), UserActivity.class);
Bundle b = new Bundle();
b.putString("loginToken", token);
b.putString("loginName", userName);
i.putExtra("logInBundle", b);
startActivity(i);
}
}
}
Accordingly to the code you posted, the following
if(b.containsKey("createBundle")) {
token = b.getString("sessionID");
name = b.getString("nameID");
} else if(b.containsKey("logInBundle")) {
token = b.getString("loginToken");
name = b.getString("loginName");
}
is wrong. onClickLog you are adding a new a Bundle with key logInBundle. What you should check with getIntent().hasExtra(String).
E.g.
if(getIntent().hasExtra("createBundle")) {
b = getIntent().getBundleExtra("createBundle");
} else if (getIntent().hasExtra("logInBundle")) {
b = getIntent().getBundleExtra("logInBundle");
}
and then read from b as you are already doing

Emails are saved in database with 0 as value

I am doing a Register login activities for my app and when I register all the info are going to my database except for the Email. I got a "0" as value in the database even if I entered a normal email address.
I checked everything in my code and my php files, but cannot find the problem.
public class createAccountActivity extends AppCompatActivity implements View.OnClickListener {
EditText etUsername,etEmail, etAge, etPassword;
Button register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createaccount);
etUsername = (EditText) findViewById(R.id.create_username);
etEmail = (EditText) findViewById(R.id.create_email);
etAge = (EditText) findViewById(R.id.create_age);
etPassword = (EditText) findViewById(R.id.create_password);
etConfirmPassword = (EditText) findViewById(R.id.confirm_password);
}
#Override
public void onClick (View v) {
switch (v.getId()){
case R.id.register:
String username = etUsername.getText().toString();
String email = etEmail.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
String password = etPassword.getText().toString();
User user = new User(username, email, age, password);
registerUser(user);
break;
}
}
private void registerUser(User user) {
ServerRequests serverRequest = new ServerRequests(this);
serverRequest.storeUserDataInBackground(user, new GetUserCallback() {
#Override
public void done(User returnedUser) {
Intent loginIntent = new Intent(createAccountActivity.this, Login.class);
startActivity(loginIntent);
}
});
}
}
In my UserLocalStore.java I got
public void storeUserData(User user) {
SharedPreferences.Editor userLocalDatabaseEditor = userLocalDatabase.edit();
userLocalDatabaseEditor.putString("username", user.username);
userLocalDatabaseEditor.putString("email", user.email);
userLocalDatabaseEditor.putString("password", user.password);
userLocalDatabaseEditor.putInt("age", user.age);
userLocalDatabaseEditor.commit();
}
My class User
public class User {
String username, email, password;
int age;
public User(String username,String email , int age, String password) {
this.username = username;
this.age = age;
this.email = email;
this.password = password;
}
public User(String username, String password) {
this(username,"", -1, password);
}
}
And my ServerRequests.class
if (jObject.length() != 0){
Log.v("happened", "2");
String username = jObject.getString("username");
int age = jObject.getInt("age");
String email = jObject.getString("email");
returnedUser = new User(username, user.username, age, user.password);
}
} catch (Exception e) {
e.printStackTrace();
}
return returnedUser;
}
Well it seems that returnedUser in ServerRequests.class puts user.username where the email should be, since you have declared it as
public User(String username,String email , int age, String password)
and it says
returnedUser = new User(username, user.username, age, user.password);
in the other file.
The Answer was simple, In my register.php it was writen "siss" and not "ssis" so it was seen as an int.
mysqli_stmt_bind_param($statement, "siss", $username, $email, $age, $password);
correct one :
mysqli_stmt_bind_param($statement, "ssis", $username, $email, $age, $password);
Sorry I should have provide it (php file), no wonder I didn't get a solution.

Categories