It always falls in 'else' condition. (TimePicker) - java

Good morning guys
1) I'm trying to do compare two time pickers and it's not working so well.
It always gives the same option of - else
int firstHouer =fromTimePicker.getCurrentHour();
int firstdMinute =fromTimePicker.getCurrentMinute();
int seccoundHouer = fromTimePicker.getCurrentHour();
int seccoundMinute =fromTimePicker.getCurrentMinute();
if (firstHouer + firstdMinute < seccoundHouer + seccoundMinute)
{
Toast toast = Toast.makeText(getApplicationContext(), "B" , Toast.LENGTH_LONG);
toast.show();
}
else
{
Toast toast = Toast.makeText(getApplicationContext(), "A" , Toast.LENGTH_LONG);
toast.show();
}
2) And I have another problem when I put the ": " symbol, the text changes it's direction
pic of the problem

If you want to compare relative 24 hour times, you should convert both the hour and minute components to the same unit, and then compare. For example, to compare both using minutes:
int firstHouer = fromTimePicker.getHour(); // getCurrentHour() is deprecated
int firstdMinute = fromTimePicker.getMinute(); // getCurrentMinute() is deprecated
int seccoundHouer = toTimePicker.getHour(); // or whatever it is called
int seccoundMinute = toTimePicker.getMinute(); // or whatever it is called
if (60*firstHouer + firstdMinute < 60*seccoundHouer + seccoundMinute) {
Toast toast = Toast.makeText(getApplicationContext(), "B" , Toast.LENGTH_LONG);
toast.show();
}
else {
Toast toast = Toast.makeText(getApplicationContext(), "A" , Toast.LENGTH_LONG);
toast.show();
}
Edit: As #Dennis just pointed out, you also have a typo in your code, and you're using the same TimePicker for both sets of times, which probably is not what you want.

You are determining the hours and minutes twice right after each other.
The execution is so fast (evenon slow machines) that the values will hardly ever be different, only right on the switch of a minute (or hour, but in that case the else will also be triggered, because of the problem described by Tim in his answer).
If you try your code very often, you will sooner or later hit exactly the point where the first getting of minutes is different and lower than the second getting, in the same hour. Then you will hit the then part.

Related

Increment an int each time Toast show something

I want to when the Toast shows message "Correct!", the TextView show score value on itself and for next times score be increment by 1. It works for first time that Toast show the message (TextView will show 1), but for second time and beyond does not work. Is that possible anyway?
int messageAnswer;
int score = 0;
if (condition is true) {
messageAnswer = R.string.correct_toast;
score++;
scoreText.setText(String.valueOf(score));
} else {
messageAnswer = R.string.incorrect_toast;
}
Toast.makeText(getApplicationContext(), messageAnswer, Toast.LENGTH_SHORT).show();
Everytime you enter this block of code, score is newly created and initialized with 0. You need to define it outside of this block, e.g. as an instance variable private int score = 0;.
It looks like your problem is that score is a local variable.
It is reset to 0 every time the function to check the answer and display the Toast is called.
You need to make it an instance variable, a field in whatever class this code is in, so that it retains its value between function calls.
You set score = 0 just before calling the toast, each time you call the toast. It should be initialized only once. You should move it upper in your program, outside the loop or however you come back here.

Convert ImageView to Integer: Android Studio

I'm trying to take the target (initiated as ImageView) id and put the integer id into a switch case to look at the adjacent Views and compare their drawables to determine if that player wins or if the game continues. I have the buttonPressed variable initiated as an Integer and used the parseInt() to get the int value of target.
public void compareButton(int buttonPressed){
//int count = 0;
ImageView adjacent;
ImageView adjacentB;
switch (buttonPressed){
case R.id.imageButtonA: //this is where adjacent buttons are identified and compared
adjacent = findViewById(R.id.imageButtonB);
adjacentB = findViewById(R.id.imageButtonC);
if (target.getDrawable() == adjacent.getDrawable() && target.getDrawable() == adjacentB.getDrawable()) {
Toast.makeText(MainActivity.this, "You Win!", Toast.LENGTH_SHORT).show(); //Win condition
// } else if (target.getDrawable() == R.id.imageButtonE.getDrawable() & target.getDrawable() == R.id.imageButtonI.getDrawable()) {
//Toast.makeText(MainActivity.this, "You Win!", Toast.LENGTH_SHORT).show(); //Win condition
// } else if (target.getDrawable() == R.id.imageButtonD.getDrawable() & target.getDrawable() == R.id.imageButtonG.getDrawable()) {
//Toast.makeText(MainActivity.this, "You Win!", Toast.LENGTH_SHORT).show(); //Win condition
}
break;
case R.id.imageButtonB:
break;
I am not filling every case for debugging purposes.
The issue I am having is when I run the emulator I get an error that says
Caused by: java.lang.NumberFormatException: For input string: "androidx.appcompat.widget.AppCompatImageButton{517eade VFED..C.. ...P..ID 45,381-304,628 #7f070072 app:id/imageButtonA}"
at java.lang.Integer.parseInt(Integer.java:521)
at java.lang.Integer.parseInt(Integer.java:556)
at com.example.connect3.MainActivity.switchColor(MainActivity.java:75)
Here is the code for the OnClickListener:
public void switchColor(View view) {
//Button pressed, depending on user, switch's to that users color; identify adjacent button ID's; toast player control switch
if (player == 1) {
source = findViewById(R.id.yellow);
target = findViewById(view.getId());
target.setImageDrawable(source.getDrawable());
buttonPressed = Integer.parseInt(target.toString());
compareButton(buttonPressed);
player++;
Toast.makeText(MainActivity.this, "Player 2's Turn!", Toast.LENGTH_SHORT).show();
} else {
source = findViewById(R.id.red);
target = findViewById(view.getId());
target.setImageDrawable(source.getDrawable());
buttonPressed = Integer.parseInt(String.valueOf(target));
compareButton(buttonPressed);
player--;
Toast.makeText(MainActivity.this, "Player 1's Turn!", Toast.LENGTH_SHORT).show();
}
Not entirely sure what is going on at this point because I thought I did everything correct but clearly something was missed. Any help would be appreciated.
change :
buttonPressed = Integer.parseInt(String.valueOf(target));
To :
buttonPressed = target.getId();
Explanation : your error says NumberFormatException means you are trying to get int value from String which is not possible to Parse or in simple your string doesn't contain proper int value and also you are passing (androidx.appcompat.widget...) as string while you have to pass button I'd

toast in Java, need to show the value of a textview

i have a resulttextview that shows the result of a computation. I would like to pass the value of the this resulttextview so that it will show in a toast.
i have this code:
Toast.makeText(MyCalcActivity.this,message, Toast.LENGTH_LONG).show();
but this code is showing the value of the firstnumberTxt where i type the first number to be calculated instead. :(
Button plusBtn = (Button) findViewById(R.id.plusButton1);
plusBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText inputOne = (EditText) findViewById(R.id.firstnumberTxt);
String message = inputOne.getText().toString();
EditText inputTwo = (EditText) findViewById(R.id.secondnumberTxt);
String message2 = inputTwo.getText().toString();
int first = Integer.parseInt(message);
int second = Integer.parseInt(message2);
int sum = first + second;
TextView resultTxt = (TextView) findViewById(R.id.resultTextview);
resultTxt.setText("Result is " + sum);
Toast.makeText(MyCalcActivity.this, message, Toast.LENGTH_LONG).show();
}
});
}
is there a way i can do this please?
I think you are a starter, and just copied the code without knowing it even.
So let me get it straight forward to you.
//Actual toast
Toast.makeText(MyCalcActivity.this, message, Toast.LENGTH_LONG).show();
// Exaplaining toast
Toast.makeText(1, 2, 3).show();
In first parameter 1, it is the activity where the toast will be
shown. Like you see in your code, it is MyCalcActivity.this which
means it is your current activity because of the input of this.
In the second parameter 2, it is what you want to be shown. See in your code you have used message and from your code, we can know that message is a string that has the value of an editText you have that is called inputOne. But you don't want that, right? You want the value of the textView resultTxt so why you are using message?! Replace message with resultText.getText() to get the value of the textview you want.
In the last parameter, which is 3. It is the length of the toast message. How long do you want it? That what it is for. In you code it is set for Long toast message which I think it is about 3 seconds. If you want a shorter one, use Toast.LENGTH_SHORT or a customized duration.
So at the end, This is your wanted code.
Toast.makeText(MyCalcActivity.this, resultTxt.getText().toString(), Toast.LENGTH_LONG)
.show();
Sorry for taking too long, but loved to help you. We all started from the bottom. But please next time search before you ask, there are a lot of similar questions and answers explaining them like this.
First you are calling message in the toast
Toast.makeText(MyCalcActivity.this, message, Toast.LENGTH_LONG).show();
Instead to display the value of sum in the toast do,
Toast.makeText(MyCalcActivity.this, sum, Toast.LENGTH_LONG).show();
Or if you want to display the value in the resultTextView, do
Toast.makeText(MyCalcActivity.this, resultText.getText().toString(), Toast.LENGTH_LONG).show();
Right now you're putting message into the toast, the value of "firstnumberTxt", instead of using the result that you just finished calculating.
All you need to do is use the result in the toast:
Toast.makeText(MyCalcActivity.this, sum, Toast.LENGTH_LONG).show();
You can also go the long way and get what is in the TextView:
Toast.makeText(MyCalcActivity.this, resultText.getText().toString(), Toast.LENGTH_LONG).show();
Button plusBtn = (Button) findViewById(R.id.plusButton1);
plusBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText inputOne = (EditText) findViewById(R.id.firstnumberTxt);
String message = inputOne.getText().toString();
EditText inputTwo = (EditText) findViewById(R.id.secondnumberTxt);
String message2 = inputTwo.getText().toString();
int first = Integer.parseInt(message);
int second = Integer.parseInt(message2);
int sum = first + second;
TextView resultTxt = (TextView) findViewById(R.id.resultTextview);
resultTxt.setText(String.valueOf(sum));
Toast.makeText(MyCalcActivity.this,"Result is" + resultTxt, Toast.LENGTH_LONG).show();
}
});
}

How to write code that if something happens nothing else happens afterward?

Lets say if the last level of a game is beaten then you dont show a dialog box asking if the player wants to go on to the next level, but rather to the mainmenu. SO basically if something happens the things that are supposed to happen afterward dont.
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
final ImageIcon pokeballIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\pokeball5.gif");
final ImageIcon pokemoneggIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\nidoking.gif");
final ImageIcon pokemonredIcon = new ImageIcon("C:\\Users\\bacojul15\\Pictures\\red.gif");
String userAnswer = answertextArea.getText().trim();
if (userAnswer.equalsIgnoreCase(answers.get(questionNumber))) {
answerLabel.setText("Correct");
levelScore ++;
triviagui.totalScore ++;
} else {
answerLabel.setText("Incorrect");
}
answertextArea.setText("");
questionNumber++;
if(questionNumber == questions.size()){
JOptionPane.showMessageDialog(null, "Your score for this level was : " + levelScore + " out of 10. \n Your total score is " + triviagui.totalScore, "Scores",JOptionPane.INFORMATION_MESSAGE, pokeballIcon );
if(difficulty == 3){
JOptionPane.showMessageDialog(null, "Good job you beat the game! \n Your total score was " + triviagui.totalScore + " out of 30.", "Thanks for playing!", JOptionPane.INFORMATION_MESSAGE, pokemonredIcon);
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
int leveloptionPane = JOptionPane.showConfirmDialog(null,"Would you like to go on to the next level?" , "Next Level?", JOptionPane.YES_NO_OPTION, levelScore, pokemoneggIcon);
if(leveloptionPane == JOptionPane.YES_OPTION){
difficulty++;
triviagui.questionFrame.setVisible(false);
triviagui.questionFrame=new QuestionFrame(difficulty);
triviagui.questionFrame.setVisible(true);
}
if(leveloptionPane == JOptionPane.NO_OPTION){
triviagui.questionFrame.setVisible(false);
triviagui.mainFrame.setVisible(true);
}
return;
}
updateQuestionScore();
}
You simply want to do:
if(something happens) {
return;
}
If you want to jump out from method use
return;
example of something like that:
public void myMethod(){
if(mynumber==5){
doThis();
}else{
return;
}
/*
*do something else <- this wont be executed if number doesnt equal 5
*cause we are already out of method.
*/
}
If you dont want to jump out from whole method bud only form part of it for instance loop.
break;
example of that:
public void myMethod(String[] stringArr){
for(String s:stringArr){
if(s.equals("hello")){
break; //get me out of this loop now !
}else{
s+="alriight";
}
}
}
doSomethingElse();//this will be executed even if you go thru break; you are still inside method dont forget.You are just out of loop
}
There are better uses for that maybe examples aint best bud you will understand how to use it form this:).
When you use break or return.In eclipse for instance you will be shown Where you actually exit. it will highlight "}"
There are several ways to do this:
You can return from a method.
You can break to exit a loop or continue to start the next iteration of the loop.
You can use an 'else' to only execute other code if the first section did not execute.
You can set a boolean flag variable and then check for that elsewhere in your code.
Depending on what you are trying to do each of these is sometimes the best way, sometimes not the best way.

OnClickListener and Toast not cooperating

I've been working on this program for an Android app assignment, and though Eclipse has no problems with the code, my phone can't seem to run it. I am a novice in Android programming, so please bear with me.
This Android app is a simple "Guess My Number" game in a blank activity. The user is to guess from 1-100, enter their answer inside a EditText view, and submit it with a push of a button. The design is fine, but getting it to work with OnClickListener is a hassle. The app crashes on my GS3 as soon as I press the button. The most troubling part is getting the button to act and give outputs in the form of Toast.
Attached is the code from MainActivity.java.
I managed to pick up different snippets of code through StackOverflow as well as a bit of Java that I knew. The result is imperfect; it was worth trying though.
You may see my complete project here. Thank you for your time, and I appreciate whatever help I can get.
package com.lookjohn.guessnumber;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Random random;
Button button;
EditText text;
int input;
int MIN = 1, MAX = 100;
int comp;
int guesses;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
random = new Random();
button = (Button)findViewById(R.id.button1);
text = (EditText)findViewById(R.id.editText1);
comp = random.nextInt(MAX - MIN + 1) + MIN;
guesses = 0;
button.setOnClickListener(myhandler1);
}
View.OnClickListener myhandler1 = new View.OnClickListener() {
public void onClick(View v) {
String value = text.getText().toString(); // Get value from input from editTextView
input = Integer.parseInt(value); // Turn string into integer
do{
guesses++;
if(input > comp)
Toast.makeText(MainActivity.this,
"Number is too big.",
Toast.LENGTH_SHORT).show();
else if (input < comp)
Toast.makeText(MainActivity.this,
"Number is too small.",
Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this,
"Good job! That was correct." +
"You made " + guesses + " guesses.",
Toast.LENGTH_SHORT).show();
} while(input != comp);
}
};
Edit: I've found a couple other issues in your code. First, your EditText's input type is phone. It should be number. Also, a user can submit a blank edit text, which will cause the app to crash when you call parseInt. I've taken care of that in some changes to your code below.
The problem is in your loop. After submit is pressed, you are entering an infinite loop. I think you are expecting the user to be able to submit multiple guesses. But if the user has entered "3" and your computed value is "10", all your loop is doing is determining that 3 != 10 over and over and over again. This causes the UI to freeze.
Removing your while loop will allow the Toast to show:
public void onClick(View v) {
// If you want to implement a max number of guesses, detect the
// number of guesses and return from the method.
if (guesses > 5) {
Toast.makeText(MainActivity.this, "Out of guesses!", Toast.LENGTH_SHORT);
return;
}
String value = text.getText().toString(); // Get value from input from editTextView
// If the user submits an empty EditText, return so we don't crash when parsing int
if (value.isEmpty()) {
Toast.makeText(MainActivity.this, "You must enter a guess!", Toast.LENGTH_SHORT);
return;
}
input = Integer.parseInt(value); // Turn string into integer
guesses++;
if(input > comp)
Toast.makeText(MainActivity.this,
"Number is too big.",
Toast.LENGTH_SHORT).show();
else if (input < comp)
Toast.makeText(MainActivity.this,
"Number is too small.",
Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this,
"Good job! That was correct." +
"You made " + guesses + " guesses.",
Toast.LENGTH_SHORT).show();
}
And in your main.xml, change your inputType from phone to number:
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignRight="#+id/button1"
android:layout_centerVertical="true"
android:ems="10"
android:inputType="number" />
You have made the infinite loop in your click listener for the guess variable which is always getting incremented and doesn't stops.
Just remove the do{...}while loop and then try out. As there doesn't seems to require any use of it.
if(input > comp)
Toast.makeText(MainActivity.this,
"Number is too big.",
Toast.LENGTH_SHORT).show();
else if (input < comp)
Toast.makeText(MainActivity.this,
"Number is too small.",
Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this,
"Good job! That was correct." +
"You made " + guesses + " guesses.",
Toast.LENGTH_SHORT).show();

Categories