Unable to use boolean values in IF statements - java

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.

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

Firebase Android Java - Can't get value of a child

So I have been trying to implement a way to check if the user had already sent a friend a request to the profile visited, or if the user has received a friend request from the profile visited. Based on the results, the buttons will be set to sent request, accept request ,add friend or friends
However, in my Firebase function, the first 3 if statements aren't met, even if one of them was supposed to be met. The first else if statement should have worked because I already sent a friend request to the profile visited.
When I ran a debug, it shows something like value = {sentFriendRequests={jmarston=2}}. So Firebase knows that I added John Marston as a friend, but for some reason the else if statement wasn't working. Its the else statement that works instead
My code is down below:
checkFriendRequestStatus function
private void checkFriendRequestStatus(final ButtonStatus buttonsCallback, final String strSignedInUID, final String visitedUsername, final String strVisitedUID) {
final DatabaseReference checkFriendRequestsRef = database.getReference("friend_requests/test/" + strSignedInUID);
checkFriendRequestsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// choice is 1 to show buttons, then select which buttons to show with second params
if (dataSnapshot.child("friends/" + visitedUsername).getValue(String.class) == strVisitedUID) {
buttonsCallback.setButtonStatus(1, 1);
}
else if (dataSnapshot.child("sentFriendRequest/" + visitedUsername).getValue(String.class) == strVisitedUID) {
buttonsCallback.setButtonStatus(1, 2);
}
else if (dataSnapshot.child("receivedFriendRequests/" + visitedUsername).getValue(String.class) == strVisitedUID) {
buttonsCallback.setButtonStatus(1, 3);
}
else {
buttonsCallback.setButtonStatus(1, 4);;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
onViewCreated function
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
sRFullName = (TextView) view.findViewById(R.id.sRUFullNameET);
addFriendBtn = (Button) view.findViewById(R.id.sRUAddFriendBtn);
sentRequestBtn = (Button) view.findViewById(R.id.sRUFriendReqSentBtn);
acceptRequestBtn = (Button) view.findViewById(R.id.sRUAcceptRequestBtn);
wereFriendsBtn = (Button) view.findViewById(R.id.sRUWeFriendsBtn);
final String strVisitedUserID = getArguments().getString("sRUserID");
final String visitedUsername = getArguments().getString("sRUsername");
ShPreference = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// converts Stringed userID back to Int
final String strSignedInUID = ShPreference.getInt(currentUserID, 0) + "";
final String signedInUsername = ShPreference.getString(currentUsername, "");
// converts the userSignedIn id to string
//final String strSignedInUID = userSignedInID + "";
// checks if the current User visited has been sent a friend Request
checkFriendRequestStatus(new ButtonStatus() {
#Override
public void setButtonStatus(int choice, int button) {
/**
* The choice params is for the choose if to show or hide buttons.
* The buttons params selects which buttons are to show or hide
*/
addFriendBtn.setVisibility(View.GONE);
sentRequestBtn.setVisibility(View.GONE);
acceptRequestBtn.setVisibility(View.GONE);
wereFriendsBtn.setVisibility(View.GONE);
// if choosed to show buttons
if (choice == 1) {
// show buttons depending on the friendRequest status
if (button == 1) {
wereFriendsBtn.setVisibility(View.VISIBLE);
}
else if (button == 2) {
sentRequestBtn.setVisibility(View.VISIBLE);
}
else if (button == 3) {
acceptRequestBtn.setVisibility(View.VISIBLE);
}
else {
addFriendBtn.setVisibility(View.VISIBLE);
}
}
}
}, strSignedInUID, visitedUsername, strVisitedUserID);
// sets the name with the Full Name; called from SearchResultsAdapter
sRFullName.setText(getArguments().getString("sRFullName"));
}
To compare String object use equals instead of == (double equals). Double equals will compare reference not their values.
Update your code of comparison like below:
private void checkFriendRequestStatus(final ButtonStatus buttonsCallback, final String strSignedInUID, final String visitedUsername, final String strVisitedUID) {
final DatabaseReference checkFriendRequestsRef = database.getReference("friend_requests/test/" + strSignedInUID);
checkFriendRequestsRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// choice is 1 to show buttons, then select which buttons to show with second params
if (dataSnapshot.child("friends/" + visitedUsername).getValue(String.class).equals(strVisitedUID)) {
buttonsCallback.setButtonStatus(1, 1);
}
else if (dataSnapshot.child("sentFriendRequest/" + visitedUsername).getValue(String.class).equals(strVisitedUID)) {
buttonsCallback.setButtonStatus(1, 2);
}
else if (dataSnapshot.child("receivedFriendRequests/" + visitedUsername).getValue(String.class).equals(strVisitedUID)) {
buttonsCallback.setButtonStatus(1, 3);
}
else {
buttonsCallback.setButtonStatus(1, 4);;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

Firebase Session Management: Issues with instatiating Global User

I'm a Android Studio coding beginner and currently building a nutrition app to get programming practice. I use Firebase for Authentication and as a database to save User data.
How it works:
My app has a survey built in which asks for body specifics and taste (age, height, liked/disliked ingredients etc.). I have a class GlobalUser with public static attributes to save the answers in the app. When the user registers, he is sent directly to the survey activity. There he answers the questions and the results are written to the Firebase database under his UID (I use a User class with the same attributes as GlobalUser to create an instance and use Firebase's setValue(Object) method). If he signs in (or still is signed in), the LoginRegistrationActivity directly sends him to the MainActivity. There, the GlobalUser class gets instantiated with the data saved under his UID. From the MainActivity, he can navigate to a ProfileActivity where the UI gets updated based on his data. This works quite well. After doing the survey I can find the results in a child node consisting of the UID of the user, the UI gets updated correctly and the sign in/registration process works as intended.
What is wrong:
However, as I was playing around with different designs and constantly restarting the app, it started to crash occasionally. After some testing it showed that the GlobalUser class wasn't updated and thus the ArrayLists were null and caused NullPointerExceptions when I used .size() on them. Since this issue only occurs rarely and seems to be related to restarting the app multiple times I thought it would have something to do with the Activity lifecycle so I also updated the GlobalUser in onStart and onResume but it didn't help. I also tried updating GlobalUser again in the ProfileActivity directly before the ArrayLists were set but it didn't work. I still guess it has something to do with the lifecycle but I have no idea where I should start. Here's the code of the relevant classes/actvitites:
LoginRegistrationActivity:
public class LoginRegistrationActivity extends AppCompatActivity {
private DatabaseReference mRef;
private FirebaseAuth mAuth;
private EditText emailAddress;
private EditText emailPassword;
private Button emailLogin;
private Button emailRegistration;
private TextView forgotPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_registration);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser()!=null){
Intent i = new Intent (LoginRegistrationActivity.this, MainActivity.class);
LoginRegistrationActivity.this.startActivity(i);
}
emailAddress = findViewById(R.id.address_edit);
emailPassword = findViewById(R.id.password_edit);
emailLogin = findViewById(R.id.mail_login_button);
emailRegistration = findViewById(R.id.mail_registration_button);
forgotPassword = findViewById(R.id.forgot_password);
emailRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = emailAddress.getText().toString().trim();
String password = emailPassword.getText().toString().trim();
if (TextUtils.isEmpty(email)){
Toast.makeText(LoginRegistrationActivity.this, "Bitte E-Mail Addresse eingeben!", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)){
Toast.makeText(LoginRegistrationActivity.this, "Bitte Passwort eingeben!", Toast.LENGTH_LONG).show();
return;
}
if (password.length()<6){
Toast.makeText(LoginRegistrationActivity.this, "Passwort muss mindestens sechs Zeichen lang sein!", Toast.LENGTH_LONG).show();
return;
}
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(LoginRegistrationActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
Toast.makeText(LoginRegistrationActivity.this, "Unbekannter Fehler", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent (LoginRegistrationActivity.this, SurveyGreetingActivity.class);
LoginRegistrationActivity.this.startActivity(i);
finish();
}
}
});
}
});
emailLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String password = emailPassword.getText().toString();
String email = emailAddress.getText().toString();
if (TextUtils.isEmpty(email)){
Toast.makeText(LoginRegistrationActivity.this, "Bitte E-Mail Addresse eingeben!", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)){
Toast.makeText(LoginRegistrationActivity.this, "Bitte Passwort eingeben!", Toast.LENGTH_LONG).show();
return;
}
if (password.length()<6){
Toast.makeText(LoginRegistrationActivity.this, "Passwort muss mindestens sechs Zeichen haben!", Toast.LENGTH_LONG).show();
return;
}
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(LoginRegistrationActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
Toast.makeText(LoginRegistrationActivity.this, "Unbekannter Fehler beim Einloggen", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent (LoginRegistrationActivity.this, MainActivity.class);
LoginRegistrationActivity.this.startActivity(i);
finish();
}
}
});
}
});
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mRef = database.getReference().child("users").child("uid").child(mAuth.getCurrentUser().getUid());
//In case the user cancelled the app when filling out the survey for the first time
if (mRef == null){
MainActivity.this.startActivity(new Intent (MainActivity.this, SurveyGreetingActivity.class));
}
//sets GlobalUser to data saved in Firebase Database User object
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user!=null){
GlobalUser.setToUser(user);
GlobalUser.setGlobalUid(mAuth.getCurrentUser().getUid());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "Database Error", Toast.LENGTH_LONG).show();
}
});
}
}
GlobalUser:
package com.example.andre.valetto02;
import java.util.ArrayList;
public class GlobalUser {
public static String globalUid = null;
public static ArrayList<Ingredient> globalLikes;
public static ArrayList<Ingredient> globalDislikes;
public static int globalAge;
public static int globalWeight;
public static int globalHeight;
public static int globalTrainingGoal;
public static int globalDailyActive;
public static boolean globalIsMale;
public GlobalUser() {
}
public static String getGlobalUid() {
return globalUid;
}
public static void setGlobalUid(String globalUid) {
GlobalUser.globalUid = globalUid;
}
public static ArrayList<Ingredient> getGlobalLikes() {
return globalLikes;
}
public static void setGlobalLikes(ArrayList<Ingredient> globalLikes) {
GlobalUser.globalLikes = globalLikes;
}
public static ArrayList<Ingredient> getGlobalDislikes() {
return globalDislikes;
}
public static void setGlobalDislikes(ArrayList<Ingredient> globalDislikes) {
GlobalUser.globalDislikes = globalDislikes;
}
public static int getGlobalAge() {
return globalAge;
}
public static void setGlobalAge(int globalAge) {
GlobalUser.globalAge = globalAge;
}
public static int getGlobalWeight() {
return globalWeight;
}
public static void setGlobalWeight(int globalWeight) {
GlobalUser.globalWeight = globalWeight;
}
public static int getGlobalHeight() {
return globalHeight;
}
public static void setGlobalHeight(int globalHeight) {
GlobalUser.globalHeight = globalHeight;
}
public static int getGlobalTrainingGoal() {
return globalTrainingGoal;
}
public static void setGlobalTrainingGoal(int globalTrainingGoal) {
GlobalUser.globalTrainingGoal = globalTrainingGoal;
}
public static int getGlobalDailyActive() {
return globalDailyActive;
}
public static void setGlobalDailyActive(int globalDailyActive) {
GlobalUser.globalDailyActive = globalDailyActive;
}
public static boolean isGlobalIsMale() {
return globalIsMale;
}
public static void setGlobalIsMale(boolean globalIsMale) {
GlobalUser.globalIsMale = globalIsMale;
}
public static void setToUser(User user) {
GlobalUser.setGlobalAge(user.getAge());
GlobalUser.setGlobalWeight(user.getWeight());
GlobalUser.setGlobalHeight(user.getHeight());
GlobalUser.setGlobalDailyActive(user.getDailyActive());
GlobalUser.setGlobalTrainingGoal(user.getTrainingGoal());
GlobalUser.setGlobalIsMale(user.getIsMale());
GlobalUser.setGlobalLikes(user.getLikes());
GlobalUser.setGlobalDislikes(user.getDislikes());
}
public static void resetLikesAndDislikes(){
globalLikes = new ArrayList <>();
globalDislikes = new ArrayList<>();
}
public static User globalToUser () {
return new User (globalLikes, globalDislikes, globalWeight, globalHeight, globalAge, globalTrainingGoal, globalDailyActive, globalIsMale);
}
}
User:
package com.example.andre.valetto02;
import java.util.ArrayList;
public class User {
ArrayList<Ingredient> likes;
ArrayList<Ingredient> dislikes;
Boolean isMale;
public Boolean getIsMale(){return isMale;}
public void setIsMale(Boolean b){isMale = b;}
public void setDislikes(ArrayList<Ingredient> dislikes) {
this.dislikes = dislikes;
}
public User (){
likes = new ArrayList<>();
dislikes = new ArrayList<>();
weight = 0;
height = 0;
age = 0;
trainingGoal = 2;
dailyActive = 1;
isMale=true;
}
public User (ArrayList<Ingredient> l, ArrayList<Ingredient> d, int w, int h, int a, int tG, int dA, boolean iM) {
likes = l;
dislikes = d;
weight = w;
height = h;
age = a;
trainingGoal = tG;
dailyActive = dA;
isMale = iM;
}
int age;
public ArrayList<Ingredient> getDislikes() {
return dislikes;
}
public ArrayList<Ingredient> getLikes() {
return likes;
}
public void setLikes (ArrayList<Ingredient> list){
likes = list;
}
public void setDisikes (ArrayList<Ingredient> list){
dislikes = list;
}
public int getAge () {
return age;
}
public void setAge (int i) {
age = i;
}
int weight;
public int getWeight (){
return weight;
}
public void setWeight(int i) {
weight = i;
}
int height;
public int getHeight (){
return height;
}
public void setHeight(int i) {
height = i;
}
int trainingGoal; //trainingGoal = 0 means weight loss, 1 means muscle gain and 2 means healthy living
public void setTrainingGoal(int i) {
trainingGoal = i;
}
public int getTrainingGoal(){
return trainingGoal;
}
int dailyActive; //dailyActive = 0 means wenig, 1 means leicht, 2 means moderat, 3 means sehr and 4 means extrem
public int getDailyActive() {return dailyActive;}
public void setDailyActive(int i) {dailyActive = i;}
public double computeCalorieGoal(){
if (isMale) {
double RMR;
RMR = weight*10 + 6.25*height - 5*age + 5;
if (dailyActive==0) {RMR=RMR*1.2;}
else if (dailyActive==1) {RMR=RMR*1.375;}
else if (dailyActive==2) {RMR=RMR*1.55;}
else if (dailyActive==3) {RMR=RMR*1.725;}
else {RMR=RMR*1.9;}
if (trainingGoal == 0) {RMR = RMR - 400;}
else if (trainingGoal ==1){RMR = RMR + 400;}
return RMR;
} else {
double RMR;
RMR = weight*10 + 6.25*height - 5*age - 161;
if (dailyActive==0) {RMR=RMR*1.2;}
else if (dailyActive==1) {RMR=RMR*1.375;}
else if (dailyActive==2) {RMR=RMR*1.55;}
else if (dailyActive==3) {RMR=RMR*1.725;}
else {RMR=RMR*1.9;}
if (trainingGoal == 0) {RMR = RMR - 300;}
else if (trainingGoal ==1){RMR = RMR + 300;}
return RMR;
}
}
}
Thanks for the help!
I just found the mistake. It has nothing to do with the activity lifecycle and it only indirectly had something to do with restarting the app. The problem was that Firebase's Value Event Listeners are still AsyncTasks. When I started the app and immediately opened the ProfileActivity, the Activity was created before the Firebase AsyncTask could fetch the data from the Database. Thus the ProfileActivity would call the .size() method on the ArrayLists before they were instantiated. In essence, the error occurred when you clicked too quickly through the UI and were faster than the asynchronous data fetching task.
Therefore I moved the session management to the LoginRegistrationActivity like this:
if (mAuth.getCurrentUser()!=null){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference mRef = firebaseDatabase.getReference().child("users").child("uid").child(mAuth.getCurrentUser().getUid());
//In case the user cancelled the app when filling out the survey for the first time
if (mRef == null){
LoginRegistrationActivity.this.startActivity(new Intent (LoginRegistrationActivity.this, SurveyGreetingActivity.class));
}
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user!=null) {
GlobalUser.setToUser(user);
GlobalUser.setGlobalUid(mAuth.getCurrentUser().getUid());
}
Intent i = new Intent (LoginRegistrationActivity.this, MainActivity.class);
LoginRegistrationActivity.this.startActivity(i);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
By moving LoginRegistrationActivity.this.startActivity(i) to the onDataChange method, I ensure that the GlobalUser variables get instantiated before the MainActivity is started. There are probably still more elegant ways to do this.

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

Categories