How to loop in Java and Android Studio - java

I have made an alarm clock app however, I am trying to make a homepage where the user can see all the alarms they have set. I want to infinitely run a block of code that updates the homepage of my app, but the methods I have found have not worked (i.e using a timer loop, while, and for loop). Any suggestion would help me a lot, also any critique to the code would help to, Thanks everyone!
I have tried
Timers, Do-While, While, and For Loops
The While loop that is in there currently cause an error and the app does not even run.
All the code I need help with is in the While Loop.
I think this is the error
(I/zygote64: Rejecting re-init on previously-failed classjava.lang.Class: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/view/View$OnUnhandledKeyEventListener;)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarms);
final Button selectAlarm1 = (Button) findViewById(R.id.selectAlarm1);
final Button selectAlarm2 = (Button) findViewById(R.id.selectAlarm2);
final Button selectAlarm3 = (Button) findViewById(R.id.selectAlarm2);
selectAlarm1.setVisibility(View.INVISIBLE);
selectAlarm2.setVisibility(View.INVISIBLE);
selectAlarm3.setVisibility(View.INVISIBLE);
final TextView textView = (TextView) findViewById(R.id.textView);
final Button createAlarm = (Button) findViewById(R.id.createAlarm);
final Button createAlarm2 = (Button) findViewById(R.id.createAlarm2);
final Button createAlarm3 = (Button) findViewById(R.id.createAlarm3);
createAlarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity();
createAlarm2.bringToFront();
}
});
createAlarm2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity2();
createAlarm3.bringToFront();
}
});
createAlarm3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMain3Activity();
}
});
selectAlarm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity();
}
});
selectAlarm2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity2();
}
});
selectAlarm3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMain3Activity();
}
});
while(true){
if (Global.intHour1 != 0 && Global.intMinute1 != 0) {
textView.setVisibility(View.GONE);
selectAlarm1.setVisibility(View.VISIBLE);
//fixing minute format
if (Global.intMinute1 <= 9) {
selectAlarm1.setText("Alarm 1 is set for " +
Global.intHour1 + ":0" + Global.intMinute1);
} else {
selectAlarm1.setText("Alarm 1 is set for " +
Global.intHour1 + ":" + Global.intMinute1);
}
} else if (Global.intHour1 == 0 && Global.intMinute1 == 0) {
textView.setVisibility(View.VISIBLE);
}
if (Global.intHour2 != 0 && Global.intMinute2 != 0) {
selectAlarm2.setVisibility(View.VISIBLE);
//fixing minute format
if (Global.intMinute2 <= 9) {
selectAlarm2.setText("Alarm 1 is set for " +
Global.intHour2 + ":0" + Global.intMinute2);
} else {
selectAlarm2.setText("Alarm 1 is set for " +
Global.intHour2 + ":" + Global.intMinute2);
}
} else {
}
if (Global.intHour3 != 0 && Global.intMinute3 != 0) {
selectAlarm3.setVisibility(View.VISIBLE);
//fixing minute format
if (Global.intMinute3 <= 9) {
selectAlarm3.setText("Alarm 1 is set for " +
Global.intHour3 + ":0" + Global.intMinute3);
} else {
selectAlarm3.setText("Alarm 1 is set for " +
Global.intHour3 + ":" + Global.intMinute3);
}
}
else {
}
if (selectAlarm1.getVisibility() == View.INVISIBLE &&
selectAlarm2.getVisibility() == View.INVISIBLE &&
selectAlarm3.getVisibility() == View.INVISIBLE) {
textView.setVisibility(View.VISIBLE);
}
else
{
}
}
}
public void openMainActivity () {
Intent openAlarm = new Intent(this, MainActivity.class);
startActivity(openAlarm);
}
public void openMainActivity2 () {
Intent openAlarm2 = new Intent(this, MainActivity2.class);
startActivity(openAlarm2);
}
public void openMain3Activity () {
Intent openAlarm3 = new Intent(this, Main3Activity.class);
startActivity(openAlarm3);
}
public void makeTextVisible () {
}
}
I want the code to recognize when the intHour1-3 and intMinute1-3 are changed and change the visibility state of a button so that when the user returns to the homepage they can see which alarms are set.

Related

preventing a user from entering multiple answer

i create a true/false quiz app. in that app i have 4 buttons i.e True,False,previous(to get back to previous question),next(to get the next question). i want to add a functionality when a user click on true or false button its get disable for that question so the user can click only once for one question.
i tried to disable the button by using button.setEnabled(false) but when i click on previous button or next button the true/false buttons enabled.i want that the user can click the answer only once it does not matter how much the user traverse the question.
i try to call the setEnabledButton() in previous on click button but it disable the button but it also disable whether the user click on answer or not.
Button btrue,bfalse,bnext,bprevious;
TextView tquestion;
int mCurrentIndex=0;
Questions[] questionbank;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btrue=findViewById(R.id.true_button);
bfalse=findViewById(R.id.false_button);
bnext=findViewById(R.id.next_button);
tquestion=findViewById(R.id.question_text);
bprevious=findViewById(R.id.previous_button);
questionbank = new Questions[]
{
new Questions(R.string.greater,false),
new Questions(R.string.Pm,true),
new Questions(R.string.capital,true),
new Questions(R.string.china,false),
new Questions(R.string.Richer,false),
new Questions(R.string.company,true),
new Questions(R.string.company1,false),
};
update();
bnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int s=questionbank.length;
if( mCurrentIndex<=s )
{
if (mCurrentIndex + 1 < questionbank.length) {
mCurrentIndex++;
}
else
{ Toast.makeText(getApplicationContext(),"not more question",Toast.LENGTH_SHORT).show();
}
update();
}
}
});
btrue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(true);
}
});
bfalse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(false);
}
});
bprevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrentIndex > 0) {
mCurrentIndex = (mCurrentIndex - 1);
update();
}
else
{ Toast.makeText(getApplicationContext(), "cant go back", Toast.LENGTH_SHORT).show(); }
}
});
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
setButtonEnabled(true);
}
private void checkAnswer(boolean userPressedTrue)
{
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
private void setButtonEnabled(boolean enabled) {
btrue.setEnabled(enabled);
bfalse.setEnabled(enabled);
}
}
In Questions class you can create a method,
public class Questions {
boolean isQuestionAnswered;
public boolean isQuestionAnswered() {
return isQuestionAnswered;
}
public void setQuestionAnswered(boolean questionAnswered) {
isQuestionAnswered = questionAnswered;
}
}
private void checkAnswer(boolean userPressedTrue)
{
questionbank[mCurrentIndex].setQuestionAnswered(true);
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
if(questionbank[mCurrentIndex].isQuestionAnswered())
setButtonEnabled(false);
else
setButtonEnabled(true);
}
Try this out and check whether this solves your problem

when i press dot button i want that dot button press only one time in input 1?

package com.deitel.calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
double input1 = 0, input2 = 0d ,count=0;
Button btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn_dot, btn_equal, btn_subtract, btn_multi, btn_add, btn_devision, btn_clear, btn_back;
TextView text_result;
boolean Addition, Subtraction, Multiplication, Devision, decimal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn0 = findViewById(R.id.btn0);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
btn7 = findViewById(R.id.btn7);
btn8 = findViewById(R.id.btn8);
btn9 = findViewById(R.id.btn9);
btn_dot = findViewById(R.id.btn_dot);
btn_equal = findViewById(R.id.btn_equal);
btn_add = findViewById(R.id.btn_add);
btn_subtract = findViewById(R.id.btn_subtract);
btn_multi = findViewById(R.id.btn_multi);
btn_devision = findViewById(R.id.btn_devision);
btn_clear = findViewById(R.id.btn_clear);
btn_back = findViewById(R.id.btn_back);
text_result = findViewById(R.id.text_result);
btn0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "0");
}
});
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "2");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "5");
}
});
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "6");
}
});
btn7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "7");
}
});
btn8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "8");
}
});
btn9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "9");
}
});
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Addition = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Subtraction = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_multi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Multiplication = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_devision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Devision = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText("");
input1 = 0.0;
input1 = 0.0;
}
});
btn_dot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(count==0){
count=1;
text_result.setText(text_result.getText()+".");
return;
}
else{
text_result.setText(text_result.getText()+"0.");
decimal=true;
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String number = text_result.getText().toString();
int input = number.length();
if (input > 0) {
text_result.setText(number.substring(0, input - 1));
}
}
});
btn_equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count=0;
if ((Addition || Subtraction || Multiplication || Devision) ) {
if (text_result.getText().toString().trim().equals("")){
input2=0;
return;
}else {
input2 = Float.parseFloat(text_result.getText() + "");
}
}
if (Addition) {
text_result.setText(input1 + input2 + "");
Addition = false;
}
if (Subtraction) {
text_result.setText(input1 - input2 + "");
Subtraction = false;
}
if (Multiplication) {
text_result.setText(input1 * input2 + "");
Multiplication = false;
}
if (Devision) {
text_result.setText(input1 / input2 + "");
Devision = false;
}
}
});
}
}
When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
But this code doesn't meet that requirements - it displays 2.3.4.5 etc..but I want only one dot in one input. When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
Here you can manage that with simple flag.
public class MainActivity extends AppCompatActivity {
// IDs of all the numeric buttons
private int[] numericButtons = {R.id.btnZero, R.id.btnOne, R.id.btnTwo, R.id.btnThree, R.id.btnFour, R.id.btnFive, R.id.btnSix, R.id.btnSeven, R.id.btnEight, R.id.btnNine};
// IDs of all the operator buttons
private int[] operatorButtons = {R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide};
// TextView used to display the output
private TextView txtScreen;
// Represent whether the lastly pressed key is numeric or not
private boolean lastNumeric;
// Represent that current state is in error or not
private boolean stateError;
// If true, do not allow to add another DOT
private boolean lastDot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
/**
* Find and set OnClickListener to numeric buttons.
*/
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
/**
* Find and set OnClickListener to operator buttons, equal button and decimal point button.
*/
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
lastDot = false; // Reset the DOT flag
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Decimal point
findViewById(R.id.btnDot).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lastNumeric && !stateError && !lastDot) {
txtScreen.append(".");
lastNumeric = false;
lastDot = true;
}
}
});
// Clear button
findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtScreen.setText(""); // Clear the screen
// Reset all the states and flags
lastNumeric = false;
stateError = false;
lastDot = false;
}
});
// Equal button
findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});
}
/**
* Logic to calculate the solution.
*/
private void onEqual() {
// If the current state is error, nothing to do.
// If the last input is a number only, solution can be found.
if (lastNumeric && !stateError) {
// Read the expression
String txt = txtScreen.getText().toString();
// Create an Expression (A class from exp4j library)
Expression expression = new ExpressionBuilder(txt).build();
try {
// Calculate the result and display
double result = expression.evaluate();
txtScreen.setText(Double.toString(result));
lastDot = true; // Result contains a dot
} catch (ArithmeticException ex) {
// Display an error message
txtScreen.setText("Error");
stateError = true;
lastNumeric = false;
}
}
}
}

TextView refuses to change text

So I'm making a game in Android Studio where you are supposed to tap the circle as many times as you can in 60 seconds.I have specific TextView's for time and the score that you achieved BUT! before the first tap the time says "Tap to start" so that the timer starts when the user want's and not on it's own.
My problem is that i have a Reset button under the circle where the user can restart back to the start the score is saved and the time should say "Tap to start" but the counter just freezes and does nothing until the user tap's again and it start's as normal.I can't figure out why it won't change it's value to "Tap to start" when i told it to do so in the On click listener from the Reset button
the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final Button button = (Button) findViewById(R.id.button);
final TextView txtview2 = (TextView) findViewById(R.id.textView2);
final TextView txtview = (TextView) findViewById(R.id.textView);
updatetime(txtview2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(started == false)
{
reverseTimer(60,txtview2,button,txtview);
started = true;
}
score++;
randnum = r.nextInt(10 - 0) + 0;
if(randnum == 0)
button.setBackground(getResources().getDrawable(R.drawable.circle));
else if(randnum == 1)
button.setBackground(getResources().getDrawable(R.drawable.circle1));
else if(randnum == 2)
button.setBackground(getResources().getDrawable(R.drawable.circle2));
else if(randnum == 3)
button.setBackground(getResources().getDrawable(R.drawable.circle3));
else if(randnum == 4)
button.setBackground(getResources().getDrawable(R.drawable.circle4));
else if(randnum == 5)
button.setBackground(getResources().getDrawable(R.drawable.circle5));
else if(randnum == 6)
button.setBackground(getResources().getDrawable(R.drawable.circle6));
else if(randnum == 7)
button.setBackground(getResources().getDrawable(R.drawable.circle7));
else if(randnum == 8)
button.setBackground(getResources().getDrawable(R.drawable.circle8));
else if(randnum == 9)
button.setBackground(getResources().getDrawable(R.drawable.circle9));
button.setText(String.valueOf(score));
}
});
Button reset_button = (Button) findViewById(R.id.button3);
reset_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Reset(txtview2,button);
started = true;
}
});
}
My reset function:
public void Reset(TextView txt,Button button)
{
updatetime(txt);
score = 0;
button.setText(String.valueOf(score));
button.setBackground(getResources().getDrawable(R.drawable.circle));
}
set high score is actuall just set score...
public void updatetime(TextView txt)
{
txt.setText("Time : Tap to start");
}
public void sethighscore(TextView txt)
{
txt.setText("Score: " + String.valueOf(score));
}
My timer that counts from 60 to 0:
public void reverseTimer(int Seconds,final TextView tv,final Button button,final TextView txt2){
CountDownTimer CountDownTimer1 = new CountDownTimer(Seconds* 1000+1000, 1000) {
public void onTick(long millisUntilFinished) {
if(clicked)
{
this.cancel();
clicked = false;
if(score > highscore)
sethighscore(txt2);
Reset(tv,button);
started = false;
}
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
Button button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked = true;
}
});
seconds = seconds % 60;
tv.setText("Time : " + String.valueOf(minutes)
+ ":" + String.valueOf(seconds));
}
public void onFinish() {
if(score > highscore)
sethighscore(txt2);
tv.setText("Completed");
Reset(tv,button);
}
}.start();
}
What happening is that textView is defined in main thread i.e UI thread. Setting text in it wont work on another thread.what u have to do is make a handler object.
Handler handler=new Handler(getApplicationContext().getMainLooper());
now the place where u want to do the textView.setText("string"); add this code there.
handler.post(new Runnable() {
#Override
public void run() {
textView.setText("string");
}
});

How to display numbers onto a textview clicked by user?

I created a calculator but I cannot display the numbers onto the TextView like every iphone/android calculator.
For example, if the user clicks 5 + 5. I want 5 + 5 to display on the textview and once you hit equals it displays 10. I've tried different ways to figure this out but I keep getting errors.
ClearBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView output = (TextView) findViewById(R.id.text_view);
output.setText("");
}
});
Button0.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "0");
}
});
Button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "1");
}
});
Button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "2");
}
});
Button3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "3");
}
});
Button4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "4");
}
});
Button5.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "5");
}
});
Button6.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "6");
}
});
Button7.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "7");
}
});
Button8.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "8");
}
});
Button9.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "9");
}
});
// Operation Buttons
addBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(textView == null) {
textView.setText(" ");
} else {
firstValue = Double.parseDouble(textView.getText() + " ");
addition = true;
textView.setText(null);
}
}
});
subBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
firstValue = Double.parseDouble(textView.getText() + " ");
subtract = true;
textView.setText(null);
}
});
divideBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
firstValue = Double.parseDouble(textView.getText() + " ");
divison = true;
textView.setText(null);
}
});
multiBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
firstValue = Double.parseDouble(textView.getText() + " ");
multiplication = true;
textView.setText(null);
}
});
equalBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
secondValue = Double.parseDouble(textView.getText() + " ");
if(addition == true) {
textView.setText(firstValue + secondValue + " ");
addition = false;
}
if(subtract == true) {
textView.setText(firstValue - secondValue + " ");
subtract = false;
}
if(divison == true) {
textView.setText(firstValue / secondValue + " ");
divison = false;
}
if(multiplication == true) {
textView.setText(firstValue * secondValue + " ");
multiplication = false;
}
}
});
NumberFormatException is an Exception that might be thrown when you
try to convert a String into a number, where that number might be an
int , a float , or any other Java numeric type.
You can use NumberFormat and Double .
Double result = new Double(textView.getText().toString());
NumberFormat nm = NumberFormat.getNumberInstance();
textview.setText(nm.format(result)+ "3");
Hope this helps you .
Can you please try and check whether it works
firstValue = Double.parseDouble(textView.getText().toString().replaceAll(" ",""));
Just a reference since you created multiple onClick listeners which is highly repetitive in your code. I'd recommend taking a look at at Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button? This would allow you to set a switch case for multiple buttons without making multiple onClickListeners. Good luck with your calculator!

ProgressBar with a countdowntimer - Android

I have a 20 second countdown timer successfully working on my trivia game. I want to add a ProgressBar (not a ProgressDialog) to the screen. I found the developer guide for Android confusing. I googled lots of examples and tried to combine them into my code. Right now all that displays when I run a game is an empty bar with no "progress" made during each question of the game.
QuestionView.java
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter;
ArrayList<Question> queries;
Timer cdTimer;
ProgressBar bar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
pointCounter = (TextView)findViewById(R.id.timer);
questionNumber = (TextView)findViewById(R.id.timeElapsedView);
timeCounter = (TextView)findViewById(R.id.timeCounter);
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(9);
loadQuestion();
}
public void loadQuestion() {
bar.setProgress(i);
if(i == 10) {
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(1);
if(answer == 1) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(2);
if(answer == 2) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(3);
if(answer == 3) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public void nextQuestion() {
score = score + points;
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public void startCountdownTimer() {
}
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
if(i >= 9) {
cdTimer.cancel();
endQuiz();
} else {
wrongAnswers++;
nextQuestion();
}
}
#Override
public void onTick(long millisUntilFinished) {
timeCounter.setText("Time remaining: " + (millisUntilFinished / 100));
points = (millisUntilFinished / 100) / 2;
pointCounter.setText("Points remaining: " + points);
if(i < 10) {
questionNumber.setText("Question " + (i + 1) + " of 10");
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
}
XML code
<ProgressBar
android:id="#+id/progressbar"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:visibility="visible"
style="#android:style/Widget.ProgressBar.Horizontal" />
What I am looking for is for the ProgressBar to slowly tick down until the 20 seconds the user is allotted for each question is gone.
New Answer
To do this let's add a new line to onTick():
bar.setProgress((int) Math.round(millisUntilFinished / 1000.0));
(You may need to tweak the data types, I am away from my compiler... Also I don't like the CountDownTimer class, it is inaccurate and often skips the second to last number. I wrote an alternate class here: android CountDownTimer - additional milliseconds delay between ticks)
Original Answer
I have a couple pointers:
Have you defined a maximum value for your ProgressBar?
bar.setMax(9);
I suggest loading i as the progress instead of the constant value of 10:
bar.setProgress(i);
If you still do not see any progress ensure that you are not in indeterminate mode:
bar.setIndeterminate(false);
(This assume that you are using a ProgressBar that can depict progress.)
Addition
Move this code into onCreate():
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false); // May not be necessary
bar.setMax(9);
Then move this line to loadQuestion():
bar.setProgress(i);
Otherwise the progress will never be updated since you only create one CountDownTimer and you never actually call startCountdownTimer().

Categories

Resources