How to compare objects to user input in an if statement - android-studio

Im trying to compare the users input (username and password) with the user objects (eg user1, user5) to see if they match and if they do then the user will be directed into another activity because they would've been able to successfully logged in, and if not a message will be displayed.
Ive created a class called User which I call to get the userName and password. I think a if statement will work for this to compare them by using .equal but when I try the app no matter if the input is correct or not it buts the message that the details were incorrect. Its like it is fully ignoring all my if statements apart from the last one. Can anyone tell me if there is a better way to achieve this or if there is something wrong in my code? Errors aren't showing up anywhere.
User class:
public class User {
// Instance variables
static String userName;
static String password;
static String favColor;
// User constructor
public User(String initUserName, String initPassword, String initFavColor) {
userName = initUserName;
password = initPassword;
favColor = initFavColor;
}
// Getter method to return userName
public String getUserName(){
return userName;
}
public String getPassword(){
return password;
}
public String getFavColor(){
return favColor;
}
Main Activity:
logInBt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
User user1 = new User("Jason", "Sword", "Red");
User user2 = new User("Billy", "Dinosaur", "Blue");
User user3 = new User("Zack", "Elephant", "Black");
User user4 = new User("Trini", "Tiger", "Yellow");
User user5 = new User("Kimberly", "Bird", "Pink");
String userET = userEditText.getText().toString();
String userPassword = passwordEditText.getText().toString();
if(userET.equals(user1.getUserName()) & userPassword.equals(user1.getPassword())){
Intent i = new Intent(getApplicationContext(), MainMenu.class);
startActivity(i);
} else if(userET.equals(user2.getUserName()) && userPassword.equals(user2.getPassword())){
Intent i = new Intent(getApplicationContext(), MainMenu.class);
startActivity(i);
}else {
Toast.makeText(getApplicationContext(), "Incorrect details. Please try again", Toast.LENGTH_SHORT).show();
}
}
});

The properties of an object must not be of the static type,
the static value is kept while the application is in use,
therefore, each time an instance of the object is created, it acquires a new value
Solution:
public class User {
//Instance variables
private String userName;
private String password;
private String favColor;
// User constructor
public User(String userName, String password, String favColor) {
this.userName = userName;
this.password = password;
this.favColor = favColor;
}
// Getter method to return userName
public String getUserName(){
return userName;
}
public String getPassword(){
return password;
}
public String getFavColor(){
return favColor;
}
}
I can recommend you read about static variables

Related

I am working on login button and there is an error on if statement. Don't know how to solve it

BtnReg = findViewById(R.id.btnRegister);
Button btnLogin = findViewById(R.id.btnLogin);
etUsername =findViewById(R.id.etUsername);
etPass = findViewById(R.id.etPass);
dataBase = Room.databaseBuilder(this, AppDataBase.class, "user-database.db")
.allowMainThreadQueries()
.build();
UserDao db = dataBase.userDao();
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = etUsername.getText().toString();
String password = etPass.getText().toString();
User user= userDao.getUser(username,password);
Attempt to invoke interface method 'com.example.worksheet3.Data.User
com.example.worksheet3.Data.UserDao.getUser(java.lang.String,
java.lang.String)' on a null object reference
if ( user !=null) {
Intent i = new Intent(MainActivity.this, HomeActivity.class);
startActivity(i);
}else{
Toast.makeText(MainActivity.this, "Unregistered user, or incorrect", Toast.LENGTH_SHORT).show();
}
}
});
You need to have a method() to search for the user(username and password) in your database helper. Then you can come back and call your database helper method in your if statement to login. If you don't know how to code the needed method please ShoutšŸ—£

I am having issues on Update operation in Room Database

Click Listerner on update Button. I dont know whether i should use
uid or not.I am trying to update firstname, lastname, username,
password and i dont know about uid. How can i use uid to update my
fields
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String firstName = etFirst2.getText().toString();
String lastName = etLast2.getText().toString();
String userName = etUser2.getText().toString();
String password = etPass2.getText().toString();
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "Users").allowMainThreadQueries().build();
UserDao userDao = db.userDao();
User user = userDao.updateUser(firstName,lastName,userName,password);
Toast.makeText(HomeActivity.this, "Updated", Toast.LENGTH_SHORT).show();
}
});
> userDao query statement in userDao file
#Query("update Users set firstName = :firstName, lastName= :lastName, userName= :userName, password= :password")
void updateUser(String firstName,String lastName, String userName, String password);
> This is my class Structure
#Entity(tableName = "Users")
public class User {
#PrimaryKey(autoGenerate = true)
public int uid;
public String firstName;
public String lastName;
public String userName;
public String password;
public User(String firstName, String lastName, String userName, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.password = password;
}

How to take an object from a class to another activity?

I have a login app that has to have a user class with the user information in an object. But now I'm trying to figure out how I could compare the user object with the username and password the user inputs to see if it is correct. So I need to be able to see for example if the user inserts "Jason" into the username txt and "Sword" into the password txt I need to see if it is correct and matches the one in the user class. Does anyone know how I would go about doing so? Any help would be muchly appreciated I'm just really stuck.
public class User {
static String userName;
static String password;
static String favColor;
public User(String userName, String password, String favColor){
this.userName = userName;
this.password = password;
this.favColor = favColor;
}
public class UserGroup{
// Created user Objects for each user
User user1 = new User ("Jason", "Sword", "Red");
User user2 = new User ("Billy", "Dinosaur", "Blue");
User user3 = new User ("Zack", "Elephant", "Black");
User user4 = new User ("Trini", "Tiger", "Yellow");
User user5 = new User ("Kimberly", "Bird", "Pink");
}
}
logInBt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String userET = userEditText.getText().toString();
String userPassword = passwordEditText.getText().toString();
UserGroup users = new UserGroup();
if (userET.equals(users.user1.userName)&& userPassword.equals(users.user1.password ){
// write here what you want user 1 to do after login
}else if (userET.equals(users.user2.userName)&& userPassword.equals(users.user2.password ){
// write here what you want user 2 to do after login
}
}
});
}
}
you have to make the user Class filed static to reached it any where
or you can use instate of it and i will use instate to do not change your code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button logInBt = findViewById(R.id.buttonLogIn);
final EditText userEditText = findViewById(R.id.editTextTextPersonName);
final EditText passwordEditText = findViewById(R.id.editTextTextPassword);
logInBt.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String userET = userEditText.getText().toString();
String userPassword = passwordEditText.getText().toString();
UserGroup users = new UserGroup();
if (userEt.equals(users.user1.userName)&& userPassword.equals(users.user1.password ){
// write here what you want user 1 to do after login
}else if (userEt.equals(users.user2.userName)&& userPassword.equals(users.user2.password ){
// write here what you want user 2 to do after login
}
}
});
do else if to check all the user and you can change it to a list of users to make it easer

How to store mac address

I'm writing an App with login and register, it works but I want to add something. Is it possible, when a user register his datas, to get directly from his phone the Mac Address and store it together the other datas?
For example, he has to insert name, user, password and email, when he clicks on register in the database there are all this datas and the macaddress of his phone too.
This is my RegisterActivity.java:
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created by amardeep on 10/26/2017.
*/
public class RegisterActivity extends AppCompatActivity {
//Declaration EditTexts
EditText editTextUserName;
EditText editTextEmail;
EditText editTextPassword;
//Declaration TextInputLayout
TextInputLayout textInputLayoutUserName;
TextInputLayout textInputLayoutEmail;
TextInputLayout textInputLayoutPassword;
//Declaration Button
Button buttonRegister;
//Declaration SqliteHelper
SqliteHelper sqliteHelper;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
sqliteHelper = new SqliteHelper(this);
initTextViewLogin();
initViews();
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validate()) {
String UserName = editTextUserName.getText().toString();
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
//Check in the database is there any user associated with this email
if (!sqliteHelper.isEmailExists(Email)) {
//Email does not exist now add new user to database
sqliteHelper.addUser(new User(null, UserName, Email, Password));
Snackbar.make(buttonRegister, "User created successfully! Please Login ", Snackbar.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, Snackbar.LENGTH_LONG);
}else {
//Email exists with email input provided so show error user already exist
Snackbar.make(buttonRegister, "User already exists with same email ", Snackbar.LENGTH_LONG).show();
}
}
}
});
}
//this method used to set Login TextView click event
private void initTextViewLogin() {
TextView textViewLogin = (TextView) findViewById(R.id.textViewLogin);
textViewLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
//this method is used to connect XML views to its Objects
private void initViews() {
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextUserName = (EditText) findViewById(R.id.editTextUserName);
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputLayoutUserName = (TextInputLayout) findViewById(R.id.textInputLayoutUserName);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
}
//This method is used to validate input given by user
public boolean validate() {
boolean valid = false;
//Get values from EditText fields
String UserName = editTextUserName.getText().toString();
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
//Handling validation for UserName field
if (UserName.isEmpty()) {
valid = false;
textInputLayoutUserName.setError("Please enter valid username!");
} else {
if (UserName.length() > 5) {
valid = true;
textInputLayoutUserName.setError(null);
} else {
valid = false;
textInputLayoutUserName.setError("Username is to short!");
}
}
//Handling validation for Email field
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
textInputLayoutEmail.setError("Please enter valid email!");
} else {
valid = true;
textInputLayoutEmail.setError(null);
}
//Handling validation for Password field
if (Password.isEmpty()) {
valid = false;
textInputLayoutPassword.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
textInputLayoutPassword.setError(null);
} else {
valid = false;
textInputLayoutPassword.setError("Password is to short!");
}
}
return valid;
}
}
Thank you very much!

Liferay - AutoLogin + Authenticator - Get Credentials From Request Header

I need help with Liferay Autologin and Custom Authentication.
My goal is to get credentials from header (populated by differents authentication framework) and then autologin. I have also to call some services when user login.
I've read some docs (also that one at http://www.liferay.com/community/wiki/-/wiki/Main/Developing+a+Custom+Authentication+System) but still I doesn't understand.
I've done a hook with portal.properties:
auto.login.hooks=it.mypackage.filter.AutoLoginFilter
and the class:
public class AutoLoginFilter implements AutoLogin {
public AutoLoginFilter() {
super();
}
#Override
public String[] login(HttpServletRequest req, HttpServletResponse arg1) throws AutoLoginException {
String[] credentials = new String[] { "test#liferay.com" };
return credentials;
}
}
In the example class AutoLogin I suppose to return just the username (I doesn' need to verify other credentials).
Then I create a ext with portal-ext.properties:
auth.pipeline.pre=it.mypackage.auth.MyAuthenticator
auth.pipeline.enable.liferay.check=false
and the authenticator:
public class MyAuthenticator implements Authenticator {
private static Log _log = LogFactory.getLog(SwaFiamAuthenticator.class);
#Override
public int authenticateByEmailAddress(long companyId, String emailAddress, String password,
Map<String, String[]> headerMap, Map<String, String[]> parameterMap) throws AuthException {
return authenticate();
}
#Override
public int authenticateByScreenName(long companyId, String screenName, String password,
Map<String, String[]> headerMap, Map<String, String[]> parameterMap) throws AuthException {
return authenticate();
}
#Override
public int authenticateByUserId(long companyId, long userId, String password, Map<String, String[]> headerMap,
Map<String, String[]> parameterMap) throws AuthException {
return authenticate();
}
protected int authenticate() {
_log.debug("returning SUCCESS");
return SUCCESS;
}
}
What I expect from the code is:
Every user entering the portal is automatically authenticated without seeing any login page, and is recognized as user "test#liferay.com"
What I get:
AutoLoginFilter.login is called, but the user is still redirected to login page.
MyAuthenticator never called (it's called only if I remove AutoLogin-hook and
remove also auth.pipeline.enable.liferay.check=false property).
Thanks for help.
The returned array must contains at first the userId, something like this must work:
String[] credentials = new String[3];
credentials[0] = userId;
credentials[1] = "undefined";
credentials[2] = Boolean.FALSE.toString();
the userId you can find in Control Panel -> Users ->...
or (better way) load it programmaticaly with UserLocalServiceUtil.getUserByEmailAddress(companyId, emailAddress);
the auth.pipeline is not needed for this approach.

Resources