Updating time by using static variable Android - java

I am using a menu option to set the time for a game. By default the time is set to 10 seconds. The user can set the time by clicking on the menu and then selecting a choice. I am using a custom view, so the method for changing the time is in a different class than the view.
When the user clicks on the menu option a dialog appears with a EditText as its view. The user enter a number between 5 and 60. I have to wait an entire game cycle for the time to change, so it should change on the next game..
but it does not..
It will only change if I try and change the time again.
Ex)
I change the time to 5 seconds the first time I play, expecting it to change to 5 seconds the next game cycle. In the next game cycle it does not change to 5. It will stay at the previous time. I change the time again to 30 seconds. Next game cycle, the timer now appears to have 5 seconds. If I change the time again to 40, it will appear 30.
This is where I am changing the time, on each newgame();
static int timeRemaining = 10;
public void newGame() {
timeLeft = timeRemaining; // start the countdown
// do other stuff
This is where I ask the user for input, and change the variable timeRemaining. Keep in mind they are in different classes.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
AlertDialog.Builder dialog;
dialog = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
dialog.setTitle("Enter the time limit");
dialog.setView(input);
dialog.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getInput = input.getText().toString();
try{
result = Integer.parseInt(getInput);
}catch(InputMismatchException e){
CannonView.timeRemaining = 10;
Toast.makeText((Context) getApplicationContext(), "Enter an integer", Toast.LENGTH_SHORT).show();
}
if(result < 5){
Toast.makeText((Context) getApplicationContext(), "Invalid input", Toast.LENGTH_SHORT).show();
} else if (result > 60) {
Toast.makeText((Context) getApplicationContext(), "Invalid input", Toast.LENGTH_SHORT).show();
}
Toast.makeText((Context) getApplicationContext(), "Time set changed next game", Toast.LENGTH_SHORT).show();
}
});
AlertDialog box = dialog.create();
box.show();
if(result < 5 || result > 60){
CannonView.timeRemaining = 10;
return true;
}else{
CannonView.timeRemaining = result;
return true;
}
}
return super.onOptionsItemSelected(item);
}
I change the timeRemaining here, but it does not update until I change it again. Any suggestions?

I think the error is you do not put the follwing in the onClickListener
if(result < 5 || result > 60)
CannonView.timeRemaining = 10;
else CannonView.timeRemaining = result;
It should be like this
dialog.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// your original code
if(result < 5 || result > 60)
CannonView.timeRemaining = 10;
else CannonView.timeRemaining = result;
});

Related

The textbox of the current Activity is not updated when another item is selected in the RadioButton of the previous Activity. Android/Java

The application should count the moments of inertia and moments of resistance of the profiles, and output the value of the selected profile in the TextView.
Application work:
The user enters the value of loads, deflection, length
Selects the required profile via radoiButton
Clicks on the "Execute calculation" button
The application reads and displays the value of the selected profile in the TextView
At the first launch, the application works correctly and everything is displayed. But when you exit to the previous activity to change the profile selection via radoiButton, the value of the text field does not change and remains the same as in the previous selection. Only restarting the entire application helps.
It turns out that to change the cross-section, you need to completely terminate the application each time and re-enter the data.
data input activity1
public void shvellerOnClick(View view) {
radioGroupShveller.removeAllViews();
RadioButton shvellerYRadioButton = new RadioButton(this);
RadioButton shvellerPRadioButton = new RadioButton(this);
shvellerYRadioButton.setText(R.string.shveller_Y);
shvellerPRadioButton.setText(R.string.shveller_P);
radioGroupShveller.addView(shvellerYRadioButton);
radioGroupShveller.addView(shvellerPRadioButton);
shvellerPRadioButton.setOnClickListener(radioButtonClickListener);
shvellerYRadioButton.setOnClickListener(radioButtonClickListener);
shvellerYRadioButton.setId(R.id.idShvellerYRadioButton);
shvellerPRadioButton.setId(R.id.idShvellerPRadioButton);
radioGroupShvellerX2.removeAllViews();
radioGroupDvutavr.removeAllViews();
radioGroupShvellerX2.clearCheck();
radioGroupDvutavr.clearCheck();
}
public void dvaShvelleraOnClick(View view) {
radioGroupShvellerX2.removeAllViews();
RadioButton shvellerYX2RadioButton = new RadioButton(this);
RadioButton shvellerPX2RadioButton = new RadioButton(this);
shvellerYX2RadioButton.setText(R.string.shveller_Y_x2);
shvellerPX2RadioButton.setText(R.string.shveller_P_x2);
radioGroupShvellerX2.addView(shvellerYX2RadioButton);
radioGroupShvellerX2.addView(shvellerPX2RadioButton);
shvellerYX2RadioButton.setOnClickListener(radioButtonClickListener);
shvellerPX2RadioButton.setOnClickListener(radioButtonClickListener);
shvellerYX2RadioButton.setId(R.id.idShvellerYX2RadioButton);
shvellerPX2RadioButton.setId(R.id.idShvellerPX2RadioButton);
radioGroupShveller.removeAllViews();
radioGroupDvutavr.removeAllViews();
radioGroupShvellerX2.clearCheck();
radioGroupDvutavr.clearCheck();
}
View.OnClickListener radioButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton rb = (RadioButton)v;
switch (rb.getId()) {
case R.id.idShvellerYRadioButton:
valueSelectedGost = 0;
break;
case R.id.idShvellerPRadioButton:
valueSelectedGost = 1;
break;
case R.id.idShvellerYX2RadioButton:
valueSelectedGost = 10;
break;
case R.id.idShvellerPX2RadioButton:
valueSelectedGost = 11;
break;
case R.id.idDvutavBRadioButton:
valueSelectedGost = 20;
break;
case R.id.idDvutavKRadioButton:
valueSelectedGost = 21;
break;
}
}
};
public void vypolnitRaschetOnClick(View view) {
int putGost = valueSelectedGost;
Intent performCalculationIntent = new Intent(StBalkaSchema1CopyActivity.this, StBalkaShema1RaschetCopyActivity.class);
performCalculationIntent.putExtra("gostInt", putGost);
startActivity(performCalculationIntent);
}
Activity2 calculation
Intent intent = getIntent();
int getGostInt = intent.getIntExtra("gostInt",0);
selectedProfileImageView = (ImageView) findViewById(R.id.selectedProfileImegeView);
selectedProfileTextView = (TextView) findViewById(R.id.selectedProfileTextView);
infoSelectedProfileTextView = (TextView) findViewById(R.id.infoSelectionProfileTextView);
double loadToFormula = Double.parseDouble(loadTextView.getText().toString());
double lengthToFormula = Double.parseDouble(lengthTextView.getText().toString());
double deflectionToFormula = Double.parseDouble(deflectionTextView.getText().toString());
double resultWtr = resultMmax * 100 / (1.12*2.1);
double resultItr = resultMmax * Math.pow(10, 5) * lengthMToFormula * Math.pow(10, 2) * deflectionToFormula / (10 * 2.1 * Math.pow(10, 6));
if (getGostInt >= 0 & getGostInt <= 9){
selectedProfileImageView.setImageResource(R.drawable.shveller);
if (getGostInt == 0){
ShvellerU_GOST_8240_89.addShvellerU();
infoSelectedProfileTextView.setText(ShvellerU_GOST_8240_89.getClosestInertiaResistance(resultItr, resultWtr));
selectedProfileTextView.setText(R.string.shveller_Y);
} else if (getGostInt == 1){
ShvellerP_GOST_8240_89.addShvellerP();
infoSelectedProfileTextView.setText(ShvellerP_GOST_8240_89.getClosestInertiaResistance(resultItr, resultWtr));
selectedProfileTextView.setText(R.string.shveller_P);
}else {
infoSelectedProfileTextView.setText("Профиль не выбран");
selectedProfileTextView.setText("Профиль не выбран");
}
} else if (getGostInt >= 10 & getGostInt <= 19){
selectedProfileImageView.setImageResource(R.drawable.dva_shvellera);
if(getGostInt == 10){
ShvellerUx2_GOST_8240_89.addShvellerUx2();
infoSelectedProfileTextView.setText(ShvellerUx2_GOST_8240_89.getClosestInertiaResistance(resultItr, resultWtr));
selectedProfileTextView.setText(R.string.shveller_Y_x2);
} else if (getGostInt == 11){
ShvellerPx2_GOST_8240_89.addShvellerPx2();
infoSelectedProfileTextView.setText(ShvellerPx2_GOST_8240_89.getClosestInertiaResistance(resultItr, resultWtr));
selectedProfileTextView.setText(R.string.shveller_P_x2);
} else {
infoSelectedProfileTextView.setText("Профиль не выбран");
selectedProfileTextView.setText("Профиль не выбран");
}
}
}
Profile adding method
public class ShvellerU_GOST_8240_89 extends Shveller {
public ShvellerU_GOST_8240_89(String name, double momentSoprotivleniya, double momentInertsii, double massa) {
super(name, momentSoprotivleniya, momentInertsii, massa);
}
public static void addShvellerU() {
ShvellerU_GOST_8240_89 shveller5U = new ShvellerU_GOST_8240_89("5У", 9.1,22.8,4.84);
shveller5U.putIn(shveller5U);
ShvellerU_GOST_8240_89 shveller6_5U = new ShvellerU_GOST_8240_89("6,5У", 15,48.6,5.9);
shveller6_5U.putIn(shveller6_5U);
ShvellerU_GOST_8240_89 shveller8U = new ShvellerU_GOST_8240_89("8У", 22.4,89.4,7.05);
shveller8U.putIn(shveller8U);
ShvellerU_GOST_8240_89 shveller10U = new ShvellerU_GOST_8240_89("10У", 34.8,174.0,8.59);
shveller10U.putIn(shveller10U);
}
}
The error will most likely occur in this block activity2 calculation.
if (getGostInt == 0){
ShvellerU_GOST_8240_89.addShvellerU();
infoSelectedProfileTextView.setText(ShvellerU_GOST_8240_89.getClosestInertiaResistance(resultItr, resultWtr));
selectedProfileTextView.setText(R.string.shveller_Y);
I think that this is due to the fact that when objects are added through the addShvellerU () method, they remain in memory and when a different section is selected, the addDvutavrK () method cannot overwrite another. How to solve this problem?

StatusUpdate Discord Bot

This is my code to update the Status:
String[] status = new String[] {"Version: 1.5.0", "https://discord.gg/arWEM2h", "Love Backxtar", "You want me!", "Type: ~help", "User Counter: %members"};
int next = 60;
public void onSecond() {
if(next%5 == 0) {
if(!hasStarted) {
hasStarted = true;
StatChannelCommand.onStartUp();
}
Random rand = new Random();
int i = rand.nextInt(status.length);
shardMan.getShards().forEach(jda -> {
String text = status[i].replaceAll("%members", "" + jda.getUsers().size());
jda.getPresence().setActivity(Activity.playing(text));
});
StatChannelCommand.checkStats();
if(next == 0) {
next = 60;
}
}
else {
next--;
}
}
But the String is running every second. I thought it was every 5 seconds. I did 60 sec % 5. What is wrong with this code?
When you enter the method onSecond() for the first time, the condition next%5 == 0 will be true. The variable next will not be updated, because this happens only in the else part. So, on next run of the method next will still be 60.

How to set click limit of clicking a button? click limit is equal to score over 5

How can I set a limit of clicking a button? The number of click is equal to score % 5.Example score is equal to 15 the number of click limit is equal to 3 how can I do that? my codes is not working
int score = 0;
int help = score % 5;
if (score == help) {
helpbtn.setEnabled(false);
} else {
helpbtn.setEnabled(true);
}
I put it inside of
public void onClick(View v) { }
If in the example limit is 3, then :
if(help>0)
{
//logic;
help--;
}
you can add it in else block.
I think I understand what you need now. I've made some assumptions. I added a separate button to submit answers and I added a boolean that is always true for now. I did manage to use modulo in this version though. Hope this helps.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private int score = 0;
private int help = 0;
private boolean answerCorrect = true; // dummy set always true for now
private Button answerButton = null;
private Button hlpbtn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
answerButton = (Button)findViewById(R.id.button_answer);
answerButton.setOnClickListener(this);
hlpbtn = (Button)findViewById(R.id.button_help);
hlpbtn.setOnClickListener(this);
hlpbtn.setEnabled(false);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.button_answer) {
if(answerCorrect) {
if((++score % 5) == 0) {
++help;
}
if((help > 0) && !hlpbtn.isEnabled()) {
hlpbtn.setEnabled(true);
}
}
Log.d("Quiz", "score = " + score + ", help = " + help);
} else if(view.getId() == R.id.button_help) {
if(--help <= 0) {
hlpbtn.setEnabled(false);
Log.d("Quiz", "help button disabled");
}
Log.d("Quiz", "help pressed, " + help + " remaining");
}
}
}
It sounds like you want 15 / 5 instead of 15 % 5.
15 / 5 == 3, whereas 15 % 5 == 0.
15/5 =3. Try this, this will help you to click a button 3 times.
%it gives remainder. Ie --->15%5=0

Line of code ignored

I'm trying to clean my code to make it run under 'sections'.
There's one called intro(), another one called second() and so on..
The issue comes when I switch from the first section of code (intro()) to the next one (second()) which should run a cleaning code first, but doesn't really!
The code basically writes text on a list which should look like a chat, so the intro() is the first part of text then it should clear the chat and start writing other text inside second().
This is my code, take a look:
int counter;
boolean introDone = false;
//Intro
public void intro(){
write(answers[counter], buttonText[counter]);
}
public void second(){
write("So these are the rules:", R.string.go);
}
public void hello(View view){
Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
toast.show();
if(counter <= 2){
intro();
}else if(counter == 3){
clear();
}else if (counter > 2 && counter < 5) {
second();}
counter++;
}
}
This did the trick:
//Intro
public void intro(){
write(answers[counter], buttonText[counter]);
}
public void second(){
write("So these are the rules:", R.string.go);
}
public void hello(View view) {
Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
toast.show();
if (counter <= 2) {
intro();
} else if(counter == 3) {
introDone = true;
}
if (introDone) {
clear();
introDone = false;
}
if (counter > 2 && counter < 5) {
second();
}
counter++;
}
}
How is the variable counter and the variable introDone initialized?
I assume that the variable counter have the value 0 at the start of the program, and the variable introDone is false. If that is the case, then the code into second section isn't executed. Example:
public void hello(View view){
// --> here, counter=0 and introDone=false
Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
toast.show();
intro(); // --> counter is still 0, so the variable introDone is still false
second(); // --> because introDone=false then the code is not executed
counter++;
}
I'm going to assume that the boolean introDone variable is never true. In your intro() method you have it wrapped with an if statement to check if the counter is 2 or less. It is hard to tell without the full source, but I would guess that if you changed your code to this:
//Intro
public void intro(){
//if (counter <= 2) {
// write(answers[counter], buttonText[counter]);
//}else{
introDone = true;
//}
}
public void second(){
if(introDone) {
listViewMother.setAdapter(null); //THIS SHOULD CLEAN THE LIST, BUT INSTEAD WHEN I RUN THE CODE IT LOOKS LIKE IT JUST IGNORES IT
if (counter > 2 && counter < 5) {
write("So these are the rules:", R.string.go);
}
}
}
public void hello(View view){
Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
toast.show();
intro();
second();
counter++;
}
everything would work fine.
From there you could look at the logic around how you increment the counter variable and see if that was the issue.
This example will run call intro() and second() 10 times.
public void hello(View view){
Toast toast = Toast.makeText(this, Integer.toString(counter), Toast.LENGTH_SHORT);
toast.show();
for (int counter = 0; counter < 10; counter++) {
intro();
second();
}
}

Counter is not counting correctly

I have 8 pairs of buttons (16 total), with some terms from sqlite database. I need when user connect 8 pair (correct or wrong, it does not matter) to end the game, with some popup on the end. When I place counter<7 in my code, i need to connect 8 pairs plus to click once more on some buttons (17 clicks). If I enter counter<6, then I get my popup after 7 pair and one more click(15 click). I don't get that logic. So here's the code:
final OnClickListener clickListener = new OnClickListener() {
private Button buttonClicked;
public void onClick(View v) {
if (counter < 7) {
Button button = (Button) v;
button.getBackground()
.setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x003333));
if (buttonClicked == null) {
// first button is clicked
buttonClicked = button;
// only do stuff if buttons are in different layouts
} else {
if (!button.getParent().equals(buttonClicked.getParent())) {
// second button is clicked
if (buttonClicked.getTag().equals(button.getTag())) {
// second button is clicked and same tag but different button
Toast.makeText(Spojnice.this, "Correct", Toast.LENGTH_SHORT).show();
button.getBackground()
.setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x66FF33));
buttonClicked.getBackground().setColorFilter(
new LightingColorFilter(0xFFFFFFFF, 0x66FF33));
buttonClicked.setEnabled(false);
button.setEnabled(false);
buttonClicked = null;
score.setText("Poeni: " + brojPoenaSpojnice);
counter++;
} else {
counter++;
//reset LightingColorFilter first
button.setEnabled(false);
Toast.makeText(Spojnice.this, "Wrong", Toast.LENGTH_SHORT).show();
buttonClicked = null;
}
} else {
//same button clicked show message or un toggle?
buttonClicked = button;
}
}
} else {
Intent i = new Intent(Spojnice.this, Popup_spojnice.class);
startActivity(i);
mHandler.postDelayed(mLaunchTask, 6500);
}
}
};
Since you first check for the counter, and just then increment it, after connecting 7 pairs your counter will be 6 (still <7). Next time you increment the counter it will be 7, and your first condition will be false, but it will only be checked again in the next round.
To solve it, you should check the condition (if (counter < 7)) after incrementing the counter, and not before.

Categories