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
Related
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 want to display the username on the user profile that the user inputs on the first activity. I am using SharedPreferences, but the following code does not display the username on the other activity.
This is the code on the activity where the user inputs the username:
public class MainActivity extends AppCompatActivity {
EditText userName, password;
Button b1;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userName=findViewById(R.id.usernameText);
password=findViewById(R.id.passwordText);
b1=findViewById(R.id.button);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if(binding.usernameText.length()==0 && binding.passwordText.length()==0){
binding.fillInTheBlanks.setText("Please, fill in the blanks.");
binding.passwordConstraint.setText("");
}
else{
SharedPreferences sp = getSharedPreferences("database", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Username", userName.getText().toString());
editor.apply();
binding.fillInTheBlanks.setText("");
binding.passwordConstraint.setText("");
startActivity(new Intent(v.getContext(), YourGenderActivity.class));
}
}
});
}
}
And this is the code where I want to read and display saved information from SharedPreferences:
public class MyProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_profile_activity);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String userstring = sp.getString("Username",null);
TextView username = findViewById(R.id.userName);
username.setText(userstring); //this does not do anything on the activity
}
public void homeActivity(View v){
Intent intent = new Intent(v.getContext(), HomeActivity.class);
startActivity(intent);
}
}
If there is another way to achieve this, any help is welcome.
If you just want an implementation of SharedPreferences, you can do it like that:
To write to the SharedPreferences:
SharedPreferences sp = context.getSharedPreferences("database", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Username", username);
editor.apply();
To retrieve information:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
String userstring = sp.getString("Username",null);
Another problem is the implementation of context is new Intent(v.getContext()) it could be as simple as
startActivity(this, YourGenderActivity.class));
This code snippet just uses this for the context then it is similar with next profile context this
NOTES:
Both writing and reading operations have to have the same Context.
SharedPreferences should write to inside a singleton to make it easy to set and get value
You are using 2 different SharedPreferences objects. You need to get the same one using getSharedPreferences("database", Context.MODE_PRIVATE) in both activities. By using PreferenceManager.getDefaultSharedPreferences(context), you're using a SharedPreferences object that is associated to your package name (nothing wrong with using that, but I prefer to be explicit).
You have specified a name for your shared preference named 'database'
In your second activity you must exactly get that name again so
use this in your second activity:
SharedPreferences sp = getSharedPreferences("database", MODE_PRIVATE);
String userstring = sp.getString("Username",null);
In SharedPreference you can have multiple names to arrange your data for example you can specify a name for all data related to theme,database and...
to get android default name for sharedPreference use :
SharedPreferences sp =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
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
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!
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.