Condition problems in Android Studio - java

I want to check 2 edittexts, if one of them is empty toast1 message will appear and if they are same toast2 will appear.
toast1 is working truly. but when they are same or different it shows toast1 it still says that one of them is empty
there are my codes. what need I do?
devamButton = (Button) findViewById(R.id.devamButton);
takimA = (EditText) findViewById(R.id.takimAtext);
takimB = (EditText) findViewById(R.id.takimBtext);
textTakimA = takimA.getText().toString();
textTakimB = takimB.getText().toString();
devamButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (textTakimB.isEmpty() || textTakimA.isEmpty()) {
Toast toast1 = Toast.makeText(getApplicationContext(),"team name is empty", Toast.LENGTH_LONG);
toast1.show();
}
else if (textTakimA.equals(textTakimB)) {
Toast toast2 = Toast.makeText(getApplicationContext(),"cant be same", Toast.LENGTH_LONG);
toast2.show();
}
else {
Toast toast3 = Toast.makeText(getApplicationContext(),"No problem", Toast.LENGTH_LONG);
toast3.show();
}

Grab the text from the EditText when you're clicking the devamButton button and not before. Essentially move these lines:
textTakimA = takimA.getText().toString();
textTakimB = takimB.getText().toString();
inside the onClick method. That way you'll be getting the text that's inside the EditTexts right when you need it. As you have it, you're checking it before the user has even had the chance to input anything, hence both of them being empty.

Because you have assign String object before click event fire. So when click it always take the old values.
Put those two lines in onClick event callbaack:
textTakimA = takimA.getText().toString();
textTakimB = takimB.getText().toString();
Make it as:
devamButton = (Button) findViewById(R.id.devamButton);
takimA = (EditText) findViewById(R.id.takimAtext);
takimB = (EditText) findViewById(R.id.takimBtext);
devamButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textTakimA = takimA.getText().toString();
textTakimB = takimB.getText().toString();
if (textTakimB.isEmpty() || textTakimA.isEmpty()) {
Toast toast1 = Toast.makeText(getApplicationContext(),"team name is empty", Toast.LENGTH_LONG);
toast1.show();
}
else if (textTakimA.equals(textTakimB)) {
Toast toast2 = Toast.makeText(getApplicationContext(),"cant be same", Toast.LENGTH_LONG);
toast2.show();
}
else {
Toast toast3 = Toast.makeText(getApplicationContext(),"No problem", Toast.LENGTH_LONG);
toast3.show();
}

Whenever I encounter a situation where a single button should have multiple functions depending on the condition. I do it this way:
devamButton = (Button) findViewById(R.id.devamButton);
takimA = (EditText) findViewById(R.id.takimAtext);
takimB = (EditText) findViewById(R.id.takimBtext);
textTakimA = takimA.getText().toString();
textTakimB = takimB.getText().toString();
if (textTakimB.isEmpty() || textTakimA.isEmpty()) {
devamButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"team name is empty", Toast.LENGTH_LONG).show();
}
}
else if (textTakimA.equals(textTakimB) {
devamButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"cant be same", Toast.LENGTH_LONG).show();
}
else {
devamButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"no problem", Toast.LENGTH_LONG).show();
}
}

Related

Create and show Toasts/Snackbars from within AlertDialog

I have a recyclerlistview that is populated using inputs gathered from an AlertDialog, which is spawned from a floating action button. When the positive button in the AlertDialog is pressed and all inputs are formatted correctly the SQLite db gets updated and after that the snackbar is made and shown from within the same listener.
If the input is malformatted, then toast is displayed, but also the dialog closes which i do not want
If the input is correct the dialog closes and the data gets added to the list, but the SnackBar is not showing
This is the onClickListener in my MainActivity:
#Override
public void onClick(View view)
{
switch ( view.getId() )
{
case R.id.add_item_btn:
View addDialogView = getLayoutInflater().inflate(R.layout.add_dialog, null);
final EditText addItemNameTxt = addDialogView.findViewById(R.id.add_item_name_txt);
final EditText addItemCountTxt = addDialogView.findViewById(R.id.add_item_count_txt);
// something unimportant left out
new AlertDialog.Builder(this)
.setView(addDialogView)
.setCancelable(true)
.setPositiveButton("Add", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int i)
{
if ( addItemNameTxt.getText().length() == 0 )
{
Toast.makeText(MainActivity.this, "Text cannot be empty", Toast.LENGTH_SHORT).show();
return;
}
String itemName = addItemNameTxt.getText().toString();
String itemCount = addItemCountTxt.getText().toString();
dbHelper.insertTask(itemName, Integer.parseInt(itemCount));
taskAdapter.swapCursor(dbHelper.getTasks());
dialog.dismiss();
Snackbar.make(getLayoutInflater().inflate(R.layout.activity_main, null).findViewById(R.id.rootLayout), String.format("Added \"%s (%s)\" to list", itemName, itemCount), Snackbar.LENGTH_LONG);
}
})
.create().show();
break;
}
}
It works (= not closing for toasting + snacking upon successful exit) when a button is put into the custom layout and that one is used instead of AlertDialog.PositiveButton.
final AlertDialog dialog = new AlertDialog.Builder(this)
.setView(addDialogView)
.create();
addDialogView.findViewById(R.id.add_confirm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view2) {
if ( addItemNameTxt.getText().length() == 0 )
{
Toast.makeText(MainActivity.this, "Text cannot be empty", Toast.LENGTH_SHORT).show();
return;
}
String itemName = addItemNameTxt.getText().toString();
String itemCount = addItemCountTxt.getText().toString();
dbHelper.insertTask(itemName, Integer.parseInt(itemCount));
taskAdapter.swapCursor(dbHelper.getTasks());
Snackbar.make(view, String.format("Added \"%s (%s)\" to list", itemName, itemCount), Snackbar.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();

Login modal - Android Studio

I make a modal to login, if username and password are correct another activity will open, but it always gives a wrong answer even i put a correct username and password.
This is my code :
public void Admin(View view){
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
View mView = getLayoutInflater().inflate(R.layout.activity_login, null);
final EditText username = (EditText) mView.findViewById(R.id.txt_username);
final EditText password = (EditText) mView.findViewById(R.id.txt_password);
final String user = username.getText().toString().trim();
final String pass = password.getText().toString().trim();
Button submit = (Button) mView.findViewById(R.id.btn_submit);
final AlertDialog dialog = mBuilder.create();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(user.equals("admin") && (pass.equals("admin"))){
try{
Intent intent = new Intent(MainActivity.this,InputActivity.class);
startActivity(intent);
}catch (Exception e){
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "Your Username and Password is wrong", Toast.LENGTH_SHORT).show();
}
}
});
mBuilder.setView(mView);
dialog.show();
}
Put the username and password variables inside the onClickedListener(). This will gonna fetch the current values of the variables. Declare it outside the Listener and put the implementation inside. Observe and try this code. This might help.
public class MainActivity extends Activity {
Button b1,b2;
EditText ed1,ed2;
TextView tx1;
int counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.button);
ed1 = (EditText)findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
b2 = (Button)findViewById(R.id.button2);
tx1 = (TextView)findViewById(R.id.textView3);
tx1.setVisibility(View.GONE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ed1.getText().toString().equals("admin") &&
ed2.getText().toString().equals("admin")) {try{
Intent intent = new Intent(MainActivity.this,InputActivity.class);
startActivity(intent);
}catch (Exception e){
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(getApplicationContext(), "Wrong
Credentials",Toast.LENGTH_SHORT).show();
tx1.setVisibility(View.VISIBLE);
tx1.setBackgroundColor(Color.RED);
counter--;
tx1.setText(Integer.toString(counter));
if (counter == 0) {
b1.setEnabled(false);
}
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
You are assigning the user and password values before the submit button onClick event is called, therefore the values are always going to be empty. You can fix this by moving the following lines inside the onClick(View view) method:
final String user = username.getText().toString().trim();
final String pass = password.getText().toString().trim();
This 2 line will return empty String
final String user = username.getText().toString().trim();
final String pass = password.getText().toString().trim();
Because you are getting text form EditText before user type anything.
What you actually need? You have to collect text from EditText after submit button click.
So Use thouse line inside OnCLickListener
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user = username.getText().toString().trim();
pass = password.getText().toString().trim();
if(user.equals("admin") && (pass.equals("admin"))){
try{
Intent intent = new Intent(MainActivity.this,InputActivity.class);
startActivity(intent);
}catch (Exception e){
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "Your Username and Password is wrong", Toast.LENGTH_SHORT).show();
}
}
});

Android- Error Message

I have been recently having an error when compiling my android code onto an emulator. The game is that when you click a button, it gives you a math question displayed on a textView, and user types their answer (in numbers) and clicks the button 'check' When I click that button, it always returns false.
Anyone knows how to fix this?
Java Class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
mathQuestion = findViewById(R.id.magic_textview);
redCircle = findViewById(R.id.math_ball);
yellowbox = findViewById(R.id.yellow_box);
yellowboxY = 1550f - 130f;
yellowbox.setY(yellowboxY);
yellowboxX = 472f;
yellowbox.setX(yellowboxX);
type_answer = findViewById(R.id.type_answer);
Button checkButton = findViewById(R.id.check_button);
checkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(redCircleX == yellowboxX && redCircleY == yellowboxY){
mathQuestion.setText("What is "+math_int1+" + "+math_int2+" ?");
math_int1 = r.nextInt(20);
math_int2 = r.nextInt(20)+1;
string_math_int1 = String.valueOf(math_int1);
string_math_int2 = String.valueOf(math_int2);
Button checkAnswer = findViewById(R.id.check_answer);
checkAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Error? Always returning false?
if (type_answer.getText().toString().contains (Integer.toString( math_int1 + math_int2))) {
Toast t = Toast.makeText(GameActivity.this, "Success!", Toast.LENGTH_SHORT);
t.show();
} else {
Toast t2= Toast.makeText(GameActivity.this, type_answer.getText().toString(), Toast.LENGTH_SHORT);
t2.show();
}
}
});
}else{
Toast.makeText(GameActivity.this, "Incorrect Or Error", Toast.LENGTH_SHORT).show();
}
}
});
Button upButton = findViewById(R.id.up_button);
upButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveUp();
}
});
Button downButton = findViewById(R.id.down_button);
downButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveDown();
}
});
Button leftButton = findViewById(R.id.left_button);
leftButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveLeft();
}
});
Button rightButton = findViewById(R.id.right_button);
rightButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
moveRight();
}
});
Button resetCircleXY = findViewById(R.id.reset_button);
resetCircleXY.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initCircleXY();
Toast.makeText(GameActivity.this, "Reset Ball's Position", Toast.LENGTH_SHORT).show();
}
});
upButton.performClick();
leftButton.performClick();
redCircleY = 1550f;
redCircle.setY(redCircleY);
redCircleX = 472f;
redCircle.setX(redCircleX);
}
private void moveUp(){
redCircleY -= ballMoveDis;
redCircle.setY(redCircleY);
}
private void moveDown(){
redCircleY += ballMoveDis;
redCircle.setY(redCircleY);
}
private void moveLeft(){
redCircleX += ballMoveDis;
redCircle.setX(redCircleX);
}
private void moveRight(){
redCircleX -= ballMoveDis;
redCircle.setX(redCircleX);
}
private void initCircleXY(){
redCircleY = 1550f;
redCircle.setY(redCircleY);
redCircleX = 472f;
redCircle.setX(redCircleX);
}
}
Help is greatly appreciated, Thanks
First mistake
string_math_int1 = String.valueOf(math_int1);
string_math_int2 = String.valueOf(math_int1); // this should be math_int2
BUT consider adding two strings
string_math_int1 + string_math_int2)
"10" + "20"
equals
"1020" not "30"
Maybe
if (type_answer.getText().toString().equals(String.valueOf (math_int1 + math_int2) {
Answer to newly formatted question:
Your issue has to do with comparing two strings when you want to check their int values. You could try using Integer.parseInt() on your EditText's entry. Just be aware you will need to do a try on it to catch an exception in the case of your EditText having any non numeric characters.
Answer to previous question about crash before edit:
Your crash isn't with your EditText. It is this line:
Toast.makeText(GameActivity.this,math_int1 + math_int2 , Toast.LENGTH_SHORT).show();
By passing it an int value, it is attempting to look up a string with that id. If your intent is to display the sum of those ints, it should look something like:
Toast.makeText(GameActivity.this, String.valueOf(math_int1 + math_int2), Toast.LENGTH_SHORT).show();

How do I disable a button temporarily even when the app is close?

So I created a simple login activity. The login button will be disabled for a period of time when the user failed to login 3 times.
My struggle is when I close the app and open it again the button is enabled back. How to fix this?
Here's my code:
public class LoginControl extends Activity {
private DBControl db = new DBControl(this);
int counter = 2;
Button login = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginview);
Button register = (Button) findViewById(R.id.btnCreateA);
login = (Button) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
EditText a = (EditText) findViewById(R.id.etUser);
EditText b = (EditText) findViewById(R.id.etPassword);
String user = a.getText().toString();
String pass = b.getText().toString();
String confirm = db.getUserPass(user);
if (user.equals("") || pass.equals("")) {
Toast passed = Toast.makeText(LoginControl.this, "Please input required fields.", Toast.LENGTH_LONG);
passed.show();
} else if (pass.equals(confirm)) {
Toast passed = Toast.makeText(LoginControl.this, "Sucess!", Toast.LENGTH_LONG);
passed.show();
Intent intent = new Intent(LoginControl.this, HomeControl.class).putExtra("Music", false);
startActivity(intent);
finish();
} else if (counter == 0)
// Disable button after 3 failed attempts
{
login.setEnabled(false);
Toast alert = Toast.makeText(LoginControl.this, "Login Disabled for 5 mins", Toast.LENGTH_LONG);
alert.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
login.setEnabled(true);
counter = 2;
}
}, 30000);
} else {
Toast passed = Toast.makeText(LoginControl.this, "Username or password don't match!", Toast.LENGTH_LONG);
counter--;
passed.show();
}
} catch (Exception e) {
Toast passed = Toast.makeText(LoginControl.this, e.toString(), Toast.LENGTH_LONG);
passed.show();
}
}
});
}
}
To get this information, even if the app is restarted, you need to save the time when the button will be enabled again. When your app starts you can open this information and check if it is before or after this time.
There are several methods, how you can store information on android:
Shared Preferences: https://developer.android.com/training/basics/data-storage/shared-preferences.html
SQLite Database: https://developer.android.com/training/basics/data-storage/databases.html
Save as File: https://developer.android.com/training/basics/data-storage/files.html
For your problem I would suggest that you should use Shared Preferences.
Using shared preferences, save the state of your button after login.setEnabled(false):
SharedPreferences prefs = this.getSharedPreferences("MyApp", Context.MODE_PRIVATE);
boolean enabled = login.isEnabled();
prefs.edit().putBoolean("LOGIN_ENABLED_KEY", enabled).apply();
Just after getting hold of the login button in onCreate, check for the presence of this value (using true as the default value):
SharedPreferences prefs = this.getSharedPreferences("MyApp", Context.MODE_PRIVATE);
boolean enabled = prefs.getBoolean("LOGIN_ENABLED_KEY", true);
login.setEnabled(enabled);
If the button is disabled at this point, you need to restart the timer so that it eventually gets enabled:
if (!enabled) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
login.setEnabled(true);
prefs.edit().clear().apply();
counter = 2;
}
}, 30000);
}
When the timer elapses:
SharedPreferences prefs = this.getSharedPreferences("MyApp", Context.MODE_PRIVATE);
prefs.edit().putBoolean("LOGIN_ENABLED_KEY", true).apply();
Alternatively, just clear the shared preferences:
SharedPreferences prefs = this.getSharedPreferences("MyApp", Context.MODE_PRIVATE);
prefs.edit().clear().apply();
Putting it all together, something roughly like this:
int counter = 2;
Button login = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginview);
final SharedPreferences prefs = this.getSharedPreferences("MyApp", Context.MODE_PRIVATE);
login = (Button) findViewById(R.id.btnLogin);
boolean enabled = prefs.getBoolean("LOGIN_ENABLED_KEY", true);
login.setEnabled(enabled);
if (!enabled) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
login.setEnabled(true);
prefs.edit().clear().apply();
counter = 2;
}
}, 30000);
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
EditText a = (EditText) findViewById(R.id.etUser);
EditText b = (EditText) findViewById(R.id.etPassword);
String user = a.getText().toString();
String pass = b.getText().toString();
if (user.equals("") || pass.equals("")) {
Toast passed = Toast.makeText(LoginControl.this, "Please input required fields.", Toast.LENGTH_LONG);
passed.show();
} else if (pass.equals("pass")) {
Toast passed = Toast.makeText(LoginControl.this, "Success!", Toast.LENGTH_LONG);
passed.show();
// Start HomeControl + finish()
} else if (counter == 0) {
// Disable button after 3 failed attempts
login.setEnabled(false);
prefs.edit().putBoolean("LOGIN_ENABLED_KEY", false).apply();
Toast alert = Toast.makeText(LoginControl.this, "Login Disabled for 5 mins", Toast.LENGTH_LONG);
alert.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
login.setEnabled(true);
prefs.edit().clear().apply();
counter = 2;
}
}, 30000);
} else {
Toast passed = Toast.makeText(LoginControl.this, "Username or password don't match!", Toast.LENGTH_LONG);
counter--;
passed.show();
}
} catch (Exception e) {
Toast passed = Toast.makeText(LoginControl.this, e.toString(), Toast.LENGTH_LONG);
passed.show();
}
}
});
}
(There is clearly room for some refactoring here, but this does work.)

Java: generate random String with (Button)

My code was running good, but just one times. I need repeating when ===> ok = (Button) findViewById(R.id.btnOk);
Is click.
This is the code
String questionNumber = "";
EditText answer;
Button ok;
TextView question;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
answer = (EditText) findViewById(R.id.answer);
ok = (Button) findViewById(R.id.btnOk);
question = (TextView) findViewById(R.id.TextViewQuestion);
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (answer.getText().toString().equals(questionNumber)) {
Toast.makeText(getBaseContext(),"Input True", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Input Wrong", Toast.LENGTH_LONG).show();
}
}
});
}
}
Do this..
String questionNumber = "";
EditText answer;
Button ok;
TextView question;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
answer = (EditText) findViewById(R.id.answer);
ok = (Button) findViewById(R.id.btnOk);
question = (TextView) findViewById(R.id.TextViewQuestion);
getRandomQuestion();
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (answer.getText().toString().equals(questionNumber)) {
Toast.makeText(getBaseContext(),"Input True", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Input Wrong", Toast.LENGTH_LONG).show();
}
getRandomQuestion();
}
});
}
private void getRandomQuestion() {
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
}
Remember to put the getRandomQuestion() below the checker because if you put it above then I believe it will always show the Input Wrong toast unless the first random number will be the same as the second random number.
For example..
You generated a random question in onCreate and let's say it is 1..
Then you put 1 in your editText so you assume that it should show Input True, right? But if you put the getRandomQuestion above the checker.. what will happen is you will generate a random question again then it will be 2..
Then, in your checker.. your answer is 1 then the question is 2.. so it will not be equal.
here your solution
put this
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
in the button listner
EDIT:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (answer.getText().toString().equals(questionNumber)) {
Toast.makeText(getBaseContext(),"Input True", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Input Wrong", Toast.LENGTH_LONG).show();
}
Random random = new Random();
questionNumber = String.format("%04d",random.nextInt(10000));
question.setText(questionNumber);
}
});

Categories