Please how can i apply this code to my android application. I am making an application that gives access to the User by entering the correct password.
I seem to be getting an error with the Console
public static void main (String args[]) throws IOException {
Console c=System.console();
String login = c.readLine("Enter your login: ");
char [] oldPassword = c.readPassword("Enter your old password: ");
if (verify(login, oldPassword)) {
boolean noMatch;
do {
char [] newPassword1 =
c.readPassword("Enter your new password: ");
char [] newPassword2 =
c.readPassword("Enter new password again: ");
noMatch = ! Arrays.equals(newPassword1, newPassword2);
if (noMatch) {
c.format("Passwords don't match. Try again.%n");
} else {
change(login, newPassword1);
c.format("Password for %s changed.%n", login);
}
Arrays.fill(newPassword1, ' ');
Arrays.fill(newPassword2, ' ');
} while (noMatch);
}
Arrays.fill(oldPassword, ' ');
}
//Dummy change method.
static boolean verify(String login, char[] password) {
// this method always returns true in this example.
// modify this method to verify password according to your rules.
return true;
}
//Dummy change method.
static void change(String login, char[] password) {
// modify this method to change password according to your rules.
}
}
Yes you can re-use your verify and change apis for android but you have discard whatever in the main method.
On Android, you will be creating an Activity having three EditText (for hide user text use android:inputType="textPassword"), one for each.
Old Password
New Password
New Password Again
Then you ll have one button call it Change Password. To this Change Password button you can add onClickListenr. When user presses this Change Password button, you will fetch the text values from EditText and then user your verify and change apis to do the actual work.
You can optionally choose a Cancel button too.
Below is how screen will look:
Snippet of handling the Change button:
// Declared in your Activity class.
EditText editTextOldPass;
EditText editTextNewPass;
EditText editTextNewPassAgain;
String login = "";
public void onCreate(Bundle savedInstanceState) {
editTextOldPass = (EditText) findViewById(R.id.editTextOldPass);
editTextNewPass = (EditText) findViewById(R.id.editTextNewPass);
editTextNewPassAgain = (EditText) findViewById(R.id.editTextNewPassAgain);
Button buttonChange = (Button) findViewById(R.id.buttonChange);
buttonChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editTextNewPass.getText().equals(editTextNewPassAgain)) {
if (verify(login, editTextOldPass.getText().toString().toCharArray()))
change(login, editTextNewPass.getText().toString().toCharArray());
} else {
Log.i("PasswordActivity", "Passwords don't match. Try again.");
}
}
});
}
Related
i am trying to create a login system on android studio using java, i have tried a piece of code i have found and modifies it to my own program- i am getting errors that the tutorial cannot explain and would appreciate if someone could tell me what i'm doing wrong.
on line 10 under username it says expression expected
The else statement says there should be an if but as you can see there is ?
public void LoginButton(){
UserName = findViewById(R.id.UserName);
userPassword = findViewById(R.id.userPassword);
userPin = findViewById(R.id.userPin);
GoBtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UserName.getText().toString().equals("user");// here i would preferably link to a database but do to time restaitns i have modeled it with user
userPassword.getText().toString().equals("pass");
{
Toast.makeText(MainActivity.this, "Username and password is correct",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, StudentActivity.class);
startActivity(intent);
}
else {
Toast.makeText(MainActivity.this,"Username and password is NOT correct",
Toast.LENGTH_SHORT).show();
}
}
I need this to lead the user to the next activty if the input is correct but so far i cannot get it to run due to the errors.
Issues
You can't use a semicolon (;) right after if statement because an empty ; is also considered a statement.
If Statement is incorrect: It has to be a valid statement
Many braces ({ and }) are missing
Here is a sample code
public void LoginButton() {
UserName = findViewById(R.id.UserName);
userPassword = findViewById(R.id.userPassword);
userPin = findViewById(R.id.userPin);
GoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UserName.getText().toString().equals("user") &&
userPassword.getText().toString().equals("pass")) {
// use your code
} else {
// use your code
}
}
});
}
Suggestion: Please read more Java
your if condition syntax is wrong you need to use AND operator(&&).
change these lines
if (UserName.getText().toString().equals("user");
userPassword.getText().toString().equals("pass");
to
if((UserName.getText().toString().equals("user")) && (userPassword.getText().toString().equals("pass")))
In my application I have a booking system which allows users to book tee times for specific times during the day. When a booking has been completed the details are saved to my Firebase and the user can then close the alert dialog. When the alert dialog is then closed the button which was clicked is then made unusable. Problem is that when the user leaves the booking activity and comes back the button is then useable, and if a different user then accesses the page the button is also able to be clicked as well.
How do I solve this problem?
Should I be saving the UID of the user in the 9am child ?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
findViewById(R.id.profilebtn).setOnClickListener(this);
findViewById(R.id.booking9am).setOnClickListener(this);
book9am = (Button)findViewById(R.id.booking9am);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.profilebtn:
finish();
startActivity(new Intent(Booking.this, ProfileActivity.class));
break;
case R.id.booking9am:
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(Booking.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_booking,null);
final EditText mPlayer1 = (EditText) mView.findViewById(R.id.player1);
final EditText mPlayer2= (EditText) mView.findViewById(R.id.player2);
final EditText mPlayer3 = (EditText) mView.findViewById(R.id.player3);
final EditText mPlayer4 = (EditText) mView.findViewById(R.id.player4);
final EditText mTime = (EditText) mView.findViewById(R.id.timeedit);
final Button mBookingbtn = (Button) mView.findViewById(R.id.bookingbtn);
mBookingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String player1= mPlayer1.getText().toString().trim();
String player2= mPlayer2.getText().toString().trim();
String player4= mPlayer4.getText().toString().trim();
String player3= mPlayer3.getText().toString().trim();
if (player1.isEmpty()) {
mPlayer1.setError("Please enter player 1");
mPlayer1.requestFocus();
return;
}
if (player2.isEmpty()) {
mPlayer2.setError("Please enter player 2");
mPlayer2.requestFocus();
return;
}
if (player3.isEmpty()) {
mPlayer3.setError("Please enter player 2");
mPlayer3.requestFocus();
return;
}if (player2.isEmpty()) {
mPlayer4.setError("Please enter player 2");
mPlayer4.requestFocus();
return;
}
String playerone = mPlayer1.getText().toString();
String playertwo = mPlayer2.getText().toString();
String playerthree = mPlayer3.getText().toString();
String playerfour = mPlayer4.getText().toString();
String teetime= mTime.getText().toString().trim();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Booking").child("9am");
Map newPost = new HashMap();
newPost.put("playerone",playerone);
newPost.put("playertwo",playertwo);
newPost.put("playerthree",playerthree);
newPost.put("playerfour",playerfour);
newPost.put("teetime",teetime);
current_user_db.setValue(newPost);
Toast.makeText(Booking.this, "Booking Confirmed", Toast.LENGTH_SHORT).show();
book9am.setClickable(false);
}
});
mBuilder.setNeutralButton("Close ", new DialogInterface.OnClickListener() { // define the 'Cancel' button
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
}
}
In your onCreate method -
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Booking").child("9am");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
book9am.setClickable(false);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
well there could be multiple approaches to this problem.
One is to set a Boolean variable in local storage Shared preference against every user....
Once your click the button set the value to true and when u come back in app check if variable is true then disable button..
Second solution Store the varible against every user on firebase and check(recommended since user can change phone)
Before showing the activity you will have to make a request to your firebase to check if the booking has been completed and depending on the result make the button enabled or not.
findViewById(R.id.booking9am).setOnClickListener(this) instead of this use:-
book9am = (Button)findViewById(R.id.booking9am);
book9am.setOnClickListener(this);
and instead of book9am.setClickable(false) set book9am.setEnable(false);
OR
If you want button disable on some conditions then it can be managed at server side also.
There are two approaches to your problem, depending on your needs.
First, is saving the button's state locally (on the client side), which means that after removing and re-installing the app for example, the state will be reset as well.
In order to save the button's state "forever", you should save the wanted state on the device, and this is what SharedPreferences is made for.
This is a good example of using it.
Here is how you should implement it in your code:
public static void set_isButtonClickable(Context ctx, Boolean bool) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean("BUTTON_CLICKABLE_STATE", bool);
editor.commit();
}
public static boolean getPrefIsFirstLaunch(Context ctx) {
return getSharedPreferences(ctx).getBoolean("BUTTON_CLICKABLE_STATE",false);
}
Second, is saving the button's state on the server side. Removing and re-installing the app obviously won't change its state. Make each user a variable which called "button_state" and change it as needed:
I am getting an error when I set the counter to subtract and close the application. I get an error "cannot assign value to final variable counter". If the user logins in 3 times with no success quit the application.
final int counter = 3;
//Set the OKButton to accept onClick
OKButton.setOnClickListener(new View.OnClickListener() {
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
//display text that was inputed for userText and passText
user = userText.getText().toString();
pass = passText.getText().toString();
//create if loop which checks if user and pass equals the credentials
if (user.equals("pshivam") && pass.equals("Bway.857661")) {
//display toast access welcome
String welcome = "Access Granted.";
//Create a Toast to display the welcome string in the MainActivity.
Toast.makeText(MainActivity.this, welcome, Toast.LENGTH_SHORT).show();
setContentView(R.layout.account_main);
}
//create else if loop which checks if user or pass does not equals the credentials
else if (!user.equals("pshivam") || !pass.equals("Bway.857661")){
//displays previous entry
userText.setText(user);
passText.setText(pass);
//allows user to re-enter credentials.
user = userText.getText().toString();
pass = passText.getText().toString();
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}
}
});
}
}
Do something like this :
OKButton.setOnClickListener(new View.OnClickListener() {
int counter = 3;
#Override
//once onClick is initalized it takes user to page menu
public void onClick(View v) {
You can also call a function from inside onClick which will decrement the variable, or use a static field declared in your class
This How to increment a Counter inside an OnClick View Event and How do I use onClickListener to count the number of times a button is pressed? might help.
Edit:
What you are doing in else part doesn't make sense. You are setting text for userText and passText that you just got using getText() from these. Then you are storing these same values to user and pass. But you aren't using these variables anywhere and they get new values when onClick is called again. Why not keep it simple :
else {
//display toast access fail
String fail = "Access Denied! Please Try again.";
//Create a Toast to display the fail string in the MainActivity.
Toast.makeText(MainActivity.this, fail, Toast.LENGTH_SHORT).show();
counter--;
if(counter == 0){
finish();
}
}
I am working on a login page in an Android App.
As you know, the app must check if the username and password are valid, and then grant the user access to the application.
I have used the following code:
...
EditText un = (EditText) findViewById(R.id.username1);
EditText pw = (EditText) findViewById(R.id.password1);
String u = un.getText().toString();
String p = pw.getText().toString();
//////// Now on the click of the Login Button:
public void onClickL (View view){
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
else ///////Display a warning message: Try again
}
when I run this code this only executes the else part. why its not executing the if part? what should I do ?
The reason is that you are fetching the EditText's value while declaring the EditText. Actually you nee to fetch the Text from EditText while clicking on the button, hence you need to move you code to onClick() method like below,
#Override
public void onClick (View view)
{
String u = un.getText().toString();
String p = pw.getText().toString();
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
{
....
}
else ///////Display a warning message: Try again
{
....
}
}
please try this:
public void onClickL (View view){
u = un.getText().toString();
p = pw.getText().toString();
if ( u.equals("Android") && p.equals("1234") ) /////// move to a new activity
{
}
else ///////Display a warning message: Try again
{
}
}
try Following code
need to clear space in username if it is available.
public void onClick (View view){
String username = un.getText().toString().trim();
String password = pw.getText().toString();
if ((username.equals("Android")) && (password.equals("1234"))) {
//do something
} else{
//do something
}
}
Try this..
get the text inside Click function like below
public void onClick (View view){
String u = un.getText().toString().trim();
String p = pw.getText().toString().trim();
if ((u.equals("Android")) && (p.equals("1234"))) {
//do something
}
else{
//do something
}
}
I have an activity that has two EditText boxes, one email and one plain text. I want to check that the email box is not empty and also that is matches an email pattern before allowing the user to move on. The pattern matcher part works, but the empty string part doesn't.
I validate as the user enters data, and then set the two buttons to the be clickable or not according to whether the email is correct. However, if the box is empty, it allows the user to press the button when it shouldn't. When there is text in the box, it does the correct thing of only letting the user press the button when the email pattern has been matched.
My after text changed method:
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String enteredEmail = email.getText().toString();
if (validateEmail(enteredEmail) == true) {
image1.setImageResource(R.drawable.greentick);
play.setClickable(true);
play.setFocusable(true);
existingUser.setClickable(true);
existingUser.setFocusable(true);
}
else {
System.out.println("Invalid");
image1.setImageResource(R.drawable.redcross);
play.setClickable(false);
play.setFocusable(false);
existingUser.setClickable(false);
existingUser.setFocusable(false);
}
}
And my validateEmail() method:
public boolean validateEmail(String email) {
boolean validated = false;
if (android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() && (! email.equals("")) ) {
validated = true;
}
else {
validated = false;
}
return validated;
}
TextChanged won't fire if the user hasn't entered anything, as the text hasn't changed... You should disable the button by default.
Have you tried debugging, as this should have shown you the event isn't firing.
this is how i validate email fields (regular expressions):
private Boolean validateEmail(String email)
{
return email.matches("^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*#[a-zA-Z](-?[a-zA-Z0-9])*(\\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
}
FYI: i dont remember offhand, you may need org.apache.commons.lang3.stringutils