Android Studio - Need help looping code every second - java

I need a system that will execute this code every second. I've been looking for a while and still can't find any ways that work. I'm quite new to Java programming and programming for android so any help will be greatly appreciated.
Values n = new Values();
double num = n.getNum();
double adder = n.getAdder();
if(adder>=1) {
num += (adder * 0.1);
}
TextView t = (TextView) findViewById(R.id.textView1);
t.setText(num + "");
n.setNum(num);
Also, I'm importing values from a Values class that looks like this,
package com.example.durtle02.durtle02;
public class Values {
double num;
double cost = 30;
double adder;
public double getNum() {
return num;
}
public void setNum(double num) {
this.num = num;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public double getAdder() {
return adder;
}
public void setAdder(double adder) {
this.adder = adder;
}
}
EDIT
MainActivity.java
package com.example.durtle02.durtle02;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.sql.Time;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//making game values accessible
final Values n = new Values();
//Loading The button for adding
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double num = n.getNum();
num++;
TextView tt = (TextView) findViewById(R.id.textView1);
n.setNum(num);
tt.setText(n.getNum() + "");
}
});
final Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double num = n.getNum();
double cost = n.getCost();
double adder = n.getAdder();
if (num >= cost) {
num -= cost;
cost = cost * 1.35;
adder++;
cost = Math.round(cost);
n.setNum(num);
n.setCost(cost);
n.setAdder(adder);
TextView tl = (TextView) findViewById(R.id.textView3);
tl.setText(n.getCost() + "");
TextView tk = (TextView) findViewById(R.id.textView4);
tk.setText(n.getAdder() + " Adders");
TextView tt = (TextView) findViewById(R.id.textView1);
tt.setText(n.getNum() + "");
TextView tp = (TextView) findViewById(R.id.textView2);
tp.setText((n.getAdder() * 0.1) + "/s");
}
}
});
countDownTimer.start();
}
// Do something each second in a time frame of 60 seconds.
CountDownTimer countDownTimer = new CountDownTimer(60000, 100) {
public void onTick(long millisUntilFinished) {
Values n = new Values();
double num = n.getNum();
double adder = n.getAdder();
if(adder>=1) {
num += (adder * 0.1);
}
num++;
n.setNum(num);
}
public void onFinish() {
countDownTimer.start(); // restart again.
}
};
/*
//---------------------------------------------------------------
Values n = new Values();
double num = n.getNum();
double adder = n.getAdder();
if(adder>=1) {
num += (adder * 0.1);
}
TextView t = (TextView) findViewById(R.id.textView1);
t.setText(num + "");
n.setNum(num);
//--------------------------------------------------------------
*/
}

I think you can use CountDownTimer, something like this:
// Do something each second in a time frame of 60 seconds.
CountDownTimer countDownTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
// For every second, do something.
doSomething();
}
public void onFinish() {
countDownTimer.start(); // restart again.
}
}.start();

If your activity is in the foreground, the following code will do.
Handler mHandler= new Handler()
final Runnable runnable = new Runnable() {
#Override
public void run() {
// do your stuff here, called every second
mHandler.postDelayed(this, 1000);
}
};
// start it with:
mHandler.post(runnable);

Related

CountDownTimer for quiz can't be accessed how I need it to be

I am writing a small math's quiz with 10 questions per level. I'm trying to write a 10 second timer which has the following functions:
Moves to the next question when it runs out and restarts the timer
Restarts when a question is entered
My issue is that regardless of how I write this code, I cannot access the timer from both the "onFinish()" function as well as the rest of the program. such as "onCorrect()" I need to be able to cancel and restart an existing timer initialised in "onCreate()" however I can't then access that timer through a MyCountDownTimer class or function (I've tried using both to no avail.)
My code is below with comments to show where I need the timers to work.
package com.example.myapplication;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class Level2 extends AppCompatActivity {
int score = 0;
int q = 1;
TextView value;
TextView q_num;
TextView timer_label = findViewById(R.id.Timer);
/*public class MyCountDownTimer extends CountDownTimer {
TextView timer_label = findViewById(R.id.Timer);
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
onDone();
}
#Override
public void onTick(long millisUntilFinished) {
int temp = (int)millisUntilFinished/1000;
//do what ever You want
timer_label.setText(String.format(getResources().getString(R.string.timer_string),String.valueOf(temp)));
}
}
#Override
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level2);
q = 1;
//MyCountDownTimer t = new MyCountDownTimer(11000,1000);
Button b1 = findViewById(R.id.option1);
Button b2 = findViewById(R.id.option2);
Button b3 = findViewById(R.id.option3);
Button b4 = findViewById(R.id.option4);
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
//
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //bellow setSupportActionBar(toolbar);
getSupportActionBar().setCustomView(R.layout.action_layout);
//Gives action bar style
value = findViewById(R.id.score_value);
q_num = findViewById(R.id.question_number);
b1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b1.getText();
onCheck(ans,score);
}
});
b2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b2.getText();
onCheck(ans,score);
}
});
b3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b3.getText();
onCheck(ans,score);
}
});
b4.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b4.getText();
onCheck(ans,score);
}
});
}
public void onCheck(String ans, int score) {
TextView ans_data = findViewById(R.id.answer_data);
String correct = (String) ans_data.getText();
if (ans.contains(correct)) {
onCorrect(score);
}
else{
onWrong();
}
}
public void onCorrect(int temp){
//t.cancel()
//t.start()
temp++;
score = temp;
q++;
if(q >= 11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
value.setText(String.valueOf(score));
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
public void onDone(){
//t.start()
q++;
if(q>=11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
else{
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
}
public void onWrong(){
//t.cancel()
//t.start
q++;
if(q>=11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
else{
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
For reference;
onCheck() checks if the answer is right
onCorrect() is right
onWrong() is wrong
onDone() is when the timer runs out
The root of my issue is that I cannot put t into onDone as it's called by the MyCountDownTimer class which doesn't have access to the t called in onCreate.
Declare MyCountDownTimer t outside of onCreate() as a global variable.

Android Java : Error while running countdown timer

I need your help to find an error in my "test" android application.
Until I create the second function "setProgessBar" the app runs without error, but now the error occur everytime. To comment the function call out has no effect.
Here is the code:
package my.timer;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Timer1 extends AppCompatActivity {
private int arrayPosition = 0;
private long timeValue = 0;
private boolean indicator = false;
private double progress;
private final String[] actions = {"Phase1" , "Phase2" , "Phase3" , "Phase4"};
private final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer1);
final Button startButton = (Button) findViewById(R.id.startButton);
final TextView text1 = (TextView) findViewById(R.id.textView3);
final TextView text2 = (TextView) findViewById(R.id.actionParameter);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text2.setText(actions[arrayPosition]);
text1.setText("" + timeValue + "");
new CountDownTimer(240000, 100) {
public void onTick(long millisUntilFinished) {
timeValue = (millisUntilFinished / 1000) % 4;
text1.setText("" + timeValue + "");
if (timeValue == 3 && indicator){
if (arrayPosition < 3){
arrayPosition++;
} else {
arrayPosition = 0;
}
indicator = false;
setProgressBar(arrayPosition);
text2.setText(actions[arrayPosition]);
}
if (timeValue == 1){
indicator = true;
}
}
public void onFinish() {
text1.setText("Geschafft :)");
}
}.start();
}
});
}
private void setProgressBar(int progressStatus) {
switch (progressStatus){
case 0:
progress = progress + 0.25;
break;
case 2:
progress = progress - 0.25;
break;
}
progressBar.setProgress((int)progress);
}
}
Many thanks in advance
Tim

How to put a number decimal (###,###,###.00) in a string value

Hello all, I would like my number (resultat) seems like this ###,###,###.00. Into (resultat) in the String.valueOf from the below phrase of the below Java Code. Thanks for your answers.
result.setText("the rent is " + String.valueOf(resultat) + " currency");
package albencreation.realestateapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Rent extends AppCompatActivity {
EditText price = null;
EditText profit = null;
TextView result = null;
Button envoyer = null;
Button close = null;
Button info = null;
Button clear = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rent);
price = (EditText) findViewById(R.id.price);
profit = (EditText) findViewById(R.id.profit);
result = (TextView) findViewById(R.id.result);
envoyer = (Button) findViewById(R.id.buttcalculate);
close = (Button) findViewById(R.id.buttclose);
info = (Button) findViewById(R.id.buttinfo);
clear = (Button) findViewById(R.id.buttclear);
envoyer.setOnClickListener(envoyerListener);
close.setOnClickListener(closeListener);
info.setOnClickListener(infoListener);
clear.setOnClickListener(clearListener);
}
private OnClickListener envoyerListener = new OnClickListener() {
#Override
public void onClick(View v) {
String p = price.getText().toString();
String o = profit.getText().toString();
float pValue;
if (p.isEmpty()) {
pValue = 0;
} else {
pValue = Float.valueOf(p);
}
float oValue;
if (o.isEmpty()) {
oValue = 0;
} else {
oValue = Float.valueOf(o);
}
float resultat = oValue * pValue / 100;
result.setText("the rent is " + String.valueOf(resultat) + " currency");
}
};
private OnClickListener closeListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent jumpage = new Intent(Rent.this, MainActivity.class);
startActivity(jumpage);
}
};
private OnClickListener infoListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent jumpage = new Intent(Rent.this, Inforent.class);
startActivity(jumpage);
}
};
private OnClickListener clearListener = new OnClickListener() {
#Override
public void onClick(View v) {
price.getText().clear();
profit.getText().clear();
String defaut = "result rent";
result.setText(defaut);
}
};
}
Use DecimalFormat to format the string as you like. For integer values use # and for decimal places use 0
DecimalFormat formatter = new DecimalFormat("###,###,###.00");
String resultString = formatter.format(resultat);
result.setText("the rent is " + resultString + " currency");
try this :
import java.text.DecimalFormat;
float f = YourValue;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f));
This code for show Two Dights Hope will help you

Stucked on Loops, not sure what is the wrong

I'm a just a beginner to android & java. I'm trying to build an app that will tell you if you win or lose base on the Martingale on gambling.
My concept is, you can set your money, target and the minimum bet.
for example is if I set my current money is 1000, and my target is to get 1100, and the minimum bet is 100, the app will auto run the function for example 10 times and calculate the win rate.
now I'm stucked, the android studio shows no error, however, whenever i try to emulate the app, it show "unfortunately, app has stopped" everything seem just fine to me, i don't know how to find the error... please guide me. million thanks
package com.example.android.gambling;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
EditText cMoney = (EditText) findViewById(R.id.money);
double currentMoney = Double.parseDouble(cMoney.getText().toString());
EditText target = (EditText) findViewById(R.id.target);
double theTarget = Double.parseDouble(target.getText().toString());
EditText bet = (EditText) findViewById(R.id.bet);
double minBet = Double.parseDouble(bet.getText().toString());
boolean findRate = calRate(currentMoney, theTarget, minBet);
public void seeRate(View view) {
TextView textview = (TextView)findViewById(R.id.textView);
textview.setText("You " + winPercentage());
}
public boolean calRate(double currentMoney, double theTarget, double minBet) {
while (currentMoney>minBet){
boolean win = winRate();
if (win){
currentMoney += minBet;
minBet = minBet;
}
else {
currentMoney -= minBet;
minBet *= 2;
}
if (currentMoney>=theTarget){
return true;
}
}
return false;
}
private boolean winRate() {
double d = Math.random();
if (d < 0.5)
return true;
else
return false;
}
public int winPercentage (){
int numberWin = 0;
for (int i=0; i<=10; i++){
boolean win = calRate(currentMoney, theTarget, minBet);
if (win){
numberWin = numberWin + 1;
}
}
return numberWin/10*100;
}
}
Edit(1)
package com.example.android.gambling;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText cMoney = (EditText) findViewById(R.id.money);
double currentMoney = Double.parseDouble(cMoney.getText().toString());
EditText target = (EditText) findViewById(R.id.target);
double theTarget = Double.parseDouble(target.getText().toString());
EditText bet = (EditText) findViewById(R.id.bet);
double minBet = Double.parseDouble(bet.getText().toString());
boolean findRate = calRate(currentMoney, theTarget, minBet);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void seeRate(View view) {
TextView textview = (TextView)findViewById(R.id.textView);
textview.setText("You " + winPercentage());
}
public boolean calRate(double currentMoney, double theTarget, double minBet) {
while (currentMoney>minBet){
boolean win = winRate();
if (win){
currentMoney += minBet;
minBet = minBet;
}
else {
currentMoney -= minBet;
minBet *= 2;
}
if (currentMoney>=theTarget){
return true;
}
}
return false;
}
private boolean winRate() {
double d = Math.random();
if (d < 0.5)
return true;
else
return false;
}
public int winPercentage (){
int numberWin = 0;
for (int i=0; i<=10; i++){
boolean win = calRate(currentMoney, theTarget, minBet);
if (win){
numberWin = numberWin + 1;
}
}
return numberWin/10*100;
}
}
Do this:
private EditText cMoney;
private double currentMoney;
private EditText target;
private double theTarget;
private EditText bet;
private double minBet;
private boolean findRate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cMoney = (EditText) findViewById(R.id.money);
currentMoney = Double.parseDouble(cMoney.getText().toString());
target = (EditText) findViewById(R.id.target);
theTarget = Double.parseDouble(target.getText().toString());
bet = (EditText) findViewById(R.id.bet);
minBet = Double.parseDouble(bet.getText().toString());
findRate = calRate(currentMoney, theTarget, minBet);
}
You can't put the code like this outside of any method/constructor, unless it's static/initializer block and there's definitely no reason to use them here.
Also, I see that your parameter name in calRate is currentMoney same as your variable, try to avoid this, it may be confusing for someone else reading your code, for you and maybe even for compiler if you go too far.
Put this:
EditText cMoney = (EditText) findViewById(R.id.money);
double currentMoney = Double.parseDouble(cMoney.getText().toString());
EditText target = (EditText) findViewById(R.id.target);
double theTarget = Double.parseDouble(target.getText().toString());
EditText bet = (EditText) findViewById(R.id.bet);
double minBet = Double.parseDouble(bet.getText().toString());
boolean findRate = calRate(currentMoney, theTarget, minBet);
Inside brackets of method onCreate() and then export variables theTarget, minBet, findRate and currentMoney into fields so that they can be visible in other parts of this class.

Is my code using multithreading in Android?

I am trying to create a new thread for my app which will—of course—do all the necessary background work when I call it to prevent the UI thread from crashing. I cannot get it to work and am a little confused as to what I should do next. Here is my code:
package com.alarm.mobilegame;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class startGames extends MainActivity {
int a = (int)Math.ceil(Math.random()*100);
int b = (int)Math.ceil(Math.random()*100);
int c = (int)Math.ceil(Math.random()*100);
int d = (int)Math.ceil(Math.random()*100);
int e = (int)Math.ceil(Math.random()*10);
int f = (int)Math.ceil(Math.random()*10);
boolean A;
boolean B;
boolean C;
public void additionCalc() {
TextView addquestion;
TextView addquestion2;
addquestion = (TextView) findViewById(R.id.textView1);
addquestion2 = (TextView) findViewById(R.id.textView5);
addquestion.setText("" + a + "+");
addquestion2.setText("" + b);
}
public void substitutionCalc() {
if (d > c)
{
while(d > c)
d = (int)Math.ceil(Math.random()*100);
}
TextView subquestion;
TextView subquestion2;
subquestion = (TextView) findViewById(R.id.textView2);
subquestion2 = (TextView) findViewById(R.id.textView6);
subquestion.setText("" + c + "-");
subquestion2.setText("" + d);
}
public void multiplicationCalc() {
if (e * f < 1)
{
while(e * f < 1)
f = (int)Math.ceil(Math.random()*10);
}
TextView mulquestion;
TextView mulquestion2;
mulquestion = (TextView) findViewById(R.id.textView3);
mulquestion2 = (TextView) findViewById(R.id.textView7);
mulquestion.setText("" + e + "x");
mulquestion2.setText("" + f);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_game1);
final Button buttonMathStart = (Button) findViewById(R.id.button1);
buttonMathStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
additionCalc();
substitutionCalc();
multiplicationCalc();
}});
}
void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
checkResultsA();
checkResultsB();
checkResultsC();
}
public void checkResultsA() {
EditText aText;
aText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(aText.toString());
int d = a + b;
if (d != c) {
A = false;
}else{
A = true;
}
}
public void checkResultsB() {
EditText sText;
sText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(sText.toString());
int z = c - d;
if (d != c) {
B = false;
}
else{
B = true;
}
}
public void checkResultsC() {
EditText mText;
mText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(mText.toString());
int d = a * b;
if (d != c) {
C = false;
}
else {
C = true;
}
//runInBackground();
}
});
Button continueGame = (Button) findViewById(R.id.button2);
continueGame.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
runInBackground();
if (A || B || C == false)
{
//
}
else
{
Intent myIntent = new Intent(startGames.this, secondGame.class);
startGames.this.startActivity(myIntent);
}
}});
}
}
Your runInBackground() creates a Thread but does not start() it. The code is never run.
The thread code seems to be accessing UI elements. Generally you shouldn't touch the UI in a background thread.
Where you invoke runInBackground() in onClick() you seem to assume the thread result is already available on the next code line. It isn't.
I suggest you have a look at the AsyncTask to make background thread operations easier. It also has convenience helpers for working with the UI thread.
Also, based on the question comments it seems that you don't need a background thread in the first place. The root problem is the crash which you avoid by not running your code. To get help with the crash, have a look at exception stacktrace in logcat.
You have written the thread but seems you forgot to add code for starting the thread.
Change your runInBackground method to
void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
checkResultsA();
checkResultsB();
checkResultsC();
}
public void checkResultsA() {
EditText aText;
aText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(aText.toString());
int d = a + b;
if (d != c) {
A = false;
}else{
A = true;
}
}
public void checkResultsB() {
EditText sText;
sText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(sText.toString());
int z = c - d;
if (d != c) {
B = false;
}
else{
B = true;
}
}
public void checkResultsC() {
EditText mText;
mText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(mText.toString());
int d = a * b;
if (d != c) {
C = false;
}
else {
C = true;
}
//runInBackground();
}
}).start();

Categories