Java: generate random String with (Button) - java

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);
}
});

Related

I want to count my every right and wrong answer submitted in my quiz app and want to display score in textview

This is the method I have created to check the condition
For the right answer, I am showing the png image and the same for the wrong answer
#SuppressLint("SetTextI18n")
private void checkAnswer(boolean userPressed) {
boolean answerProvided = mQuestionBank[mCurrentIndex].isQuestionTrueAnswer();
int messageStringId = 0;
if (answerProvided == userPressed) {
messageStringId = R.string.correct_toast;
mGreenTick.setImageResource(R.drawable.green_tick);
mGreenTick.setVisibility(View.VISIBLE);
}
else {
messageStringId = R.string.incorrect_toast;
mGreenTick.setImageResource(R.drawable.red_cross);
mGreenTick.setVisibility(View.VISIBLE);
}
// Toast.makeText(MainActivity.this, messageStringId, Toast.LENGTH_SHORT).show();
}
I have called the method checkAnswer() method in the true button click and false button click below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Does nothing yet, but soon!
checkAnswer(true);
mTrueButton.setEnabled(false);
mFalseButton.setEnabled(false);
mMoreInfoButton.setVisibility(View.VISIBLE);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Does nothing yet, but soon!
checkAnswer(false);
mFalseButton.setEnabled(false);
mTrueButton.setEnabled(false);
mMoreInfoButton.setVisibility(View.VISIBLE);
}
});
Now, i have used intent method in Score Button click and in the ScoreActivity.class i want to show the
store in textview.
please tell me how to count the true answer and wrong answer and store the score in the variable which i
can show in textview
Please help me.
mScoreButton = (Button)findViewById(R.id.score_button);
mScoreButton.setVisibility(View.INVISIBLE);
mScoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScoreActivity.class);
startActivity(intent);
finish();
}
});
private int trueCount = 0;
private int falseCount = 0;
#SuppressLint("SetTextI18n")
private void checkAnswer(boolean userPressed) {
boolean answerProvided = mQuestionBank[mCurrentIndex].isQuestionTrueAnswer();
int messageStringId = 0;
if (answerProvided == userPressed) {
trueCount++;
messageStringId = R.string.correct_toast;
mGreenTick.setImageResource(R.drawable.green_tick);
mGreenTick.setVisibility(View.VISIBLE);
}
else {
falseCount++;
messageStringId = R.string.incorrect_toast;
mGreenTick.setImageResource(R.drawable.red_cross);
mGreenTick.setVisibility(View.VISIBLE);
}
// Toast.makeText(MainActivity.this, messageStringId, Toast.LENGTH_SHORT).show();
}
...
//Displaying int textView
textView.setText(String.format("Right count: %d False count: %d", rightCount, falseCount));
mFinalMarks = (TextView)findViewById(R.id.final_marks);
mFinalMarks.setText("Final Score is: " + getIntent().getStringExtra("PLUS_MARKS") + "Marks out of 10 ");
getIntent().getStringExtra("PLUS_MARKS");
// it is showing null instead of score

Condition problems in Android Studio

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();
}
}

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();

Adding a new activity on button click

I'm making a simple application and want to open a new Activity when I click a button. I have looked at a few tutorials online to do so, but I keep getting errors in my code that I dont quite know how to get rid of.
My code:
public class MainActivity extends AppCompatActivity {
private static Button button_convert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onClick_Convert();
public void onClick_Convert() {
onClick_Convert = (button_convert) findViewById(R.id.button_convert);
onClick_Convert.setOnClickListener (
new View.onClickListener() {
public void onClick (View v) {
Intent intent = new Intent("com.example.jamesk93.bmi_app.SecondActivity");
startActivity(intent);
}
}
);
}
final Button button_calc = (Button) findViewById(R.id.button_calc);
final EditText field_weight = (EditText) findViewById(R.id.field_height);
final EditText field_height = (EditText) findViewById(R.id.field_height);
final TextView view_result = (TextView) findViewById(R.id.view_result);
final TextView view_msg = (TextView) findViewById(R.id.view_msg);
button_calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View V) {
double weight;
double height;
double bmi;
String msg = "";
weight = Double.parseDouble(field_weight.getText().toString());
height = Double.parseDouble(field_height.getText().toString());
if (field_height.getText().toString().equals("") || field_weight.getText().toString().equals("")) {
Toast.makeText(getApplicationContext(), "No Valid Values", Toast.LENGTH_LONG);
} else {
bmi = height * height;
bmi = weight / bmi;
view_result.setText(String.valueOf(bmi));
if (bmi < 18.5) {
msg = "Underweight";
} else if (bmi > 18.5 && bmi < 25) {
msg = "Normal";
} else if (bmi > 25) {
msg = "Overweight";
}
view_msg.setText(msg);
}
}
});
}
}
Im pretty sure it is my use of brackets and indenting that is generating the errors. Ive tried to reposition them but it doesnt seem to be solving anything.
If I comment lines 21-33 out which is the code for the onclick intent, it runs fine. If you need to see any of my other files, just comment which ones and I'll upload them for you.
Your code should be like this:
private Button button_convert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_convert= (Button) findViewById(R.id.button_convert);
onClick_Convert();
}
public void onClick_Convert() {
button_convert.setOnClickListener (
new View.OnClickListener() {
#Override
public void onClick (View v) {
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
}
);
}
EDIT:
There are a few mistakes:
First:
You are trying to initialize "onClick Convert" but it was not declared, actually the name of your button is "button convert". And then you try to cast it with "button convert". You should cast your button with "(Button)"
Second:
You are trying to initialize your button inside the click event, you should initialized it before the event, because then your button will be null.
Third:
The correct syntax to start an activity is:
Intent intent = new Intent(YourActivity.class, NewActivity.class);
startActivity(intent);
Hope this help you, I recommend you to take a look to this link: http://developer.android.com/intl/es/training/basics/firstapp/starting-activity.html

Categories