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();
}
}
Related
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:
So I have stored password as hash in shared preferences, when user puts password I need to make a hash of it and compare with stored one.
Should it be done in AsyncTask or Thread because calculation and comparison could freeze UI? And then do you know a clean way to recieve result (true, false) from asynctask or thread?
public void startGenerateCode(View view) {
String pinCompare = pin; //pin is class variable obtained from editText
pinCompare = tools.bin2hex(tools.getHash(pinCompare));
if(pinCompare.compareTo(session.getDetails("Pin"))==0){
generateCode();
}
else
Toast.makeText(this, "Wrong PIN", Toast.LENGTH_SHORT).show();
}
public void generateCode(){
Intent i = new Intent(this, GeneratedCode.class);
startActivity(i);
overridePendingTransition(R.anim.right_slide_in, R.anim.right_slide_out);
finish();
}
This is done in activity after button is pressed.
Zolo,
I guess this process is triggered when someone presses a Button, such as login. I don't think you need any extra Thread to process the Hash calculus.
If you then have to connect to a server and send/receive data, then you should use it due to the asynchronous flow.
Response to comments on main post:
Yes, you can start an Activity in onPostExecute.
Code example:
public void startGenerateCode(View view) {
// Disable button
Button button = (Butto) view;
button.setEnabled(false);
String pinCompare = pin; //pin is class variable obtained from editText
pinCompare = tools.bin2hex(tools.getHash(pinCompare));
if(pinCompare.compareTo(session.getDetails("Pin"))==0){
generateCode();
} else {
// If the login fails, re-enable the button to try again
button.setEnabled(true);
Toast.makeText(this, "Wrong PIN", Toast.LENGTH_SHORT).show();
}
}
I did it by heart, so there may be mistakes.
I have an android app that has a Login Button, which logs in once validated information with that in the SQLite database, I also have another button that is for Register.
How can I make it so when the user Login is successful the register button is disabled and only becomes clickable when the app is closed and restarted.
Below is the code for my two buttons.
public void onClickButton(View v) {
// Login Button
if (v.getId() == R.id.Blogin) {
EditText a = (EditText) findViewById(R.id.TFusername);
String str = a.getText().toString();
EditText b = (EditText) findViewById(R.id.TFpassword);
String pass = b.getText().toString();
String password = helper.searchPass(str);
if (pass.equals(password)) {
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
} else {
// Show Toast Message
Toast temp = Toast.makeText(LoginActivity.this, "Username/ Password is incorrect!", Toast.LENGTH_SHORT);
temp.show();
}
}
// Create account Button
if (v.getId() == R.id.Bsignup) {
Intent i = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(i);
}
} // Ends onClickButtonenter code here
If you could give suggestions or point me in the right direction that would be great.
Try like this
public void onClickButton(View v) {
// Login Button
if (v.getId() == R.id.Blogin) {
EditText a = (EditText) findViewById(R.id.TFusername);
String str = a.getText().toString();
EditText b = (EditText) findViewById(R.id.TFpassword);
String pass = b.getText().toString();
String password = helper.searchPass(str);
if (pass.equals(password)) {
register_button.setEnabled(False)
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
} else {
register_button.setEnabled(True)
// Show Toast Message
Toast temp = Toast.makeText(LoginActivity.this, "Username/ Password is incorrect!", Toast.LENGTH_SHORT);
temp.show();
}
}
// Create account Button
if (v.getId() == R.id.Bsignup) {
Intent i = new Intent(LoginActivity.this, SignUpActivity.class);
startActivity(i);
}
}
Set the buttons visibility to GONE, so it will be completely removed or to INVISIBLE after you logged in.
b.setVisibility(View.GONE);
If you wont save any state after restarting the app the button will be visible again.
When you inflate the view in your Activity and you create your Button objects. You could test for the successful login and then use
if (someCheckForASuccessfulLogin){
theRegisterButton.setEnabled(false);
}
1. Make one extra field in database
Set one more field in database for checking user is already registered or not. If user register once set this field's value as "false".
2. Check field value by getting it from database
Now at login time first check this field value whether it's "true" or "false".
If value is false then write this line.
yourButtonName.setClickable(false);
if value is "true" then write yourButtonName.setClickable(true);
This will work definitely.
I'm new to stackoverflow and android, sorry if i'm wrong. I am trying to check the text fields is empty or not, when the text field is empty, upload button should show please enter title and when user enters the text then only it should upload the image. After entering title then also it again shows the toast.
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (title1.matches("")){
Toast.makeText(getApplicationContext(), "Please enter the Title and Category", Toast.LENGTH_SHORT).show();
} else if(description1.matches("")){
Toast.makeText(getApplicationContext(), "Please Select Category", Toast.LENGTH_SHORT).show();
} else {
flag = 1;
// uploading the file to server
new UploadFileToServer().execute();
}
}
});
Any help would be appreciated.
To check for empty fields, use
if(TextUtils.isEmpty(editText.getText().toString())) {
// do something
}
or if you want to check if string is empty or null use -
if(TextUtils.isEmpty(stringToCheck) {
// do something
}
try this.
Place this code in your button onClickListener:
String mText = mEditText.getText().toString();
if(TextUtils.isEmpty(mText)){
//Do what you want(Edittext is NULL)
}else{
//Do what you want(Not NULL)
}
Try to get value from your edittext like below:
Globally declare variable : -
String editvalue;
In onCreate() :-
EditText youredittext = (EditText)findViewById(R.id.youredittextid);
editvalue = youredittext.getText.toString().trim();
Now in your condition check :
if(editvalue.isEmpty() || editvalue == null){
// Do what you want when editText's value is null or empty
}else{
}
You can also use
TextUtils.isEmpty(CharSequence str)
for empty and null string check.
Returns true if the string is null or 0-length
Im trying to create a button which when pushed reads the edittext box to
Make sure its not blank
Make sure its not the default text in this case "First Name".
However when the button is pushed it still preforms the action even if the edittext text is First Name or blank. Is there an easier way to do this? Also the toast are not made when the text is First Name or blank.
createp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (fname.getText().toString() != "")
if (fname.getText().toString() != "First Name"){
prefsEditor.putInt("user", 1);
prefsEditor.commit();
}
if (fname.getText().toString() == "")
{
Toast.makeText(createactivity.this, "You need a first name to create a profile!",
Toast.LENGTH_LONG).show();
}
if (fname.getText().toString() == "First Name") {
Toast.makeText(createactivity.this, "You need a first name to create a profile!",
Toast.LENGTH_LONG).show();
}
}});
}
Try this instead:
if (!fname.getText().toString().equals(""))
...
Another example:
if (fname.getText().toString().equals("First Name"))
....