Android Java : Error while running countdown timer - java

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

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.

Fatal Exception: Timer-0?

Im creating a game which calculates reaction times. I am using a timer to get the time it takes for a user to press a button. For some reason I am getting a Timer-0 Exception when I try run the app.
LOGCAT
E/AndroidRuntime: FATAL EXCEPTION: Timer-0
Process: com.example.abz.layouts, PID: 16015
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6556)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:942)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:5081)
at android.view.View.invalidateInternal(View.java:12713)
at android.view.View.invalidate(View.java:12649)
at android.view.View.invalidateDrawable(View.java:16788)
at android.widget.TextView.invalidateDrawable(TextView.java:5408)
at android.graphics.drawable.Drawable.invalidateSelf(Drawable.java:385)
at android.graphics.drawable.RippleDrawable.invalidateSelf(RippleDrawable.java:705)
at android.graphics.drawable.RippleDrawable.invalidateSelf(RippleDrawable.java:701)
at android.graphics.drawable.LayerDrawable.invalidateDrawable(LayerDrawable.java:896)
at android.graphics.drawable.DrawableWrapper.invalidateDrawable(DrawableWrapper.java:153)
at android.graphics.drawable.Drawable.invalidateSelf(Drawable.java:385)
at android.graphics.drawable.GradientDrawable.setColorFilter(GradientDrawable.java:837)
at android.graphics.drawable.DrawableWrapper.setColorFilter(DrawableWrapper.java:243)
at android.graphics.drawable.LayerDrawable.setColorFilter(LayerDrawable.java:1285)
at android.graphics.drawable.Drawable.clearColorFilter(Drawable.java:600)
at com.example.abz.layouts.HighLight.run(HighLight.java:33)
at java.util.Timer$TimerImpl.run(Timer.java:284)
D/EGL_emulation: eglMakeCurrent: 0xae424780: ver 3 0 (tinfo 0xae412ba0)
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaaac9820
Application terminated.
Here are my java classes
MainActivty.java
package com.example.abz.layouts;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private long start_time;
private long end_time;
private Button finalButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
// Create list of buttons
ArrayList<Button> buttons = createButtonsArrayList();
// Generates sequence of 5 random buttons
RandomSequence randomSequence = new RandomSequence(buttons, 5, 9);
// Add OnClickListener for last button
finalButton = randomSequence.sequence.get(randomSequence.sequence.size() - 1);
finalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalButtonClicked();
}
});
// Start Game
start_time = System.nanoTime();
randomSequence.startSequence();
}
private void finalButtonClicked() {
end_time = System.nanoTime();
double diffInMillis = (end_time - start_time) / 1e6;
finalButton.getBackground().clearColorFilter();
Toast toast = Toast.makeText(this, "Reaction time: " + diffInMillis + " milliseconds.", Toast.LENGTH_LONG);
toast.show();
}
private ArrayList<Button> createButtonsArrayList() {
ArrayList<Button> buttons = new ArrayList<>();
final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button)findViewById(R.id.button2);
final Button button3 = (Button) findViewById(R.id.button3);
final Button button4 = (Button) findViewById(R.id.button4);
final Button button5 = (Button) findViewById(R.id.button5);
final Button button6 = (Button) findViewById(R.id.button6);
final Button button7 = (Button) findViewById(R.id.button7);
final Button button8 = (Button) findViewById(R.id.button8);
final Button button9 = (Button) findViewById(R.id.button9);
buttons.add(button1);
buttons.add(button2);
buttons.add(button3);
buttons.add(button4);
buttons.add(button5);
buttons.add(button6);
buttons.add(button7);
buttons.add(button8);
buttons.add(button9);
return buttons;
}
}
HighLight.java
package com.example.abz.layouts;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.widget.Button;
import java.util.ArrayList;
import java.util.TimerTask;
public class HighLight extends TimerTask {
private ArrayList<Button> sequence;
private int sequencePosition;
public HighLight(ArrayList<Button> sequence) {
this.sequence = sequence;
sequencePosition = 0;
}
public void run() {
Button activeButton = sequence.get(sequencePosition);
if (sequencePosition == 0) {
activeButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
} else if (sequencePosition == sequence.size() - 1) {
Button previousActiveButton = sequence.get(sequencePosition - 1);
previousActiveButton.getBackground().clearColorFilter();
activeButton.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
// TODO: PLAY SOUND FOR FINAL BUTTON
this.cancel();
} else {
Button previousActiveButton = sequence.get(sequencePosition - 1);
previousActiveButton.getBackground().clearColorFilter();
activeButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
}
sequencePosition++;
}
}
RandomSequence.java
package com.example.abz.layouts;
import android.os.Looper;
import android.widget.Button;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.logging.Handler;
public class RandomSequence {
public ArrayList<Button> sequence;
private ArrayList<Button> buttons;
private int length;
public RandomSequence(ArrayList<Button> buttons, int low, int high) {
this.buttons = buttons;
length = newRandomNumber(low, high);
sequence = generateRandomSequence();
}
public void startSequence() {
Timer timer = new Timer();
timer.schedule(new HighLight(sequence), 0, 1500);
}
private ArrayList<Button> generateRandomSequence() {
ArrayList<Button> randomSequence = new ArrayList<>();
for (int i = 1; i <= length; i++) {
int random = newRandomNumber(0, buttons.size());
Button button = buttons.get(random);
// Ensure not same number in a row
while (randomSequence.size() > 0 && button.getId() == randomSequence.get(randomSequence.size() - 1).getId()) {
random = newRandomNumber(0, buttons.size());
button = buttons.get(random);
}
randomSequence.add(buttons.get(random));
}
return randomSequence;
}
private int newRandomNumber(int low, int high) {
Random r = new Random();
return r.nextInt(high - low) + low;
}
}
I have tried looking for solutions but was not successful.
The key line in your logcat is this:
Only the original thread that created a view hierarchy can touch its views
You're trying to make changes to UI elements outside the main thread, in this case with calls to previousActiveButton.getBackground().clearColorFilter() within HighLight.run().
You can either post your run() method on a Handler created on the main thread, or wrap UI-related calls within runOnUiThread(). Because you're using a self-contained class that extends TimerTask, I recommend the former:
public void run() {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Button activeButton = sequence.get(sequencePosition);
if (sequencePosition == 0) {
activeButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
} else if (sequencePosition == sequence.size() - 1) {
Button previousActiveButton = sequence.get(sequencePosition - 1);
previousActiveButton.getBackground().clearColorFilter();
activeButton.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
// TODO: PLAY SOUND FOR FINAL BUTTON
HighLight.this.cancel();
} else {
Button previousActiveButton = sequence.get(sequencePosition - 1);
previousActiveButton.getBackground().clearColorFilter();
activeButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
}
}
});
sequencePosition++;
}
Though personally I'd look into using a recursive Handler::postDelayed() rather than a Timer

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

Android Studio - Need help looping code every second

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

How can random string look like slot machine

In my program, I have only 1 button. And first press the program will output a random string. If the user presses it again to stop, my program will slow random (delay) the same slot machine. How can I do it?
my code
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Randomsentence extends Activity {
boolean showRandom = false;
TextView txt;
int time = 30;
int random;
public String[] myString;
Button bt1;
boolean check = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
bt1 = (Button) findViewById(R.id.bt1);
Medaiplayer mp = new Medaiplayer();
Mediaplayer mp2 = new Mediaplayer();
mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1);
mp2 = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile2);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showRandom = !showRandom;
t = new Thread() {
public void run() {
try {
while (showRandom) {
mp.start();
mp2.reset();
mp2.prepare();
sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
mp.reset();
mp.prepare();
mp2.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
t.start();
}
});
}
// our handler
Handler handler = new Handler() {
public void handleMessage(Message msg) {//display each item in a single line
{
Random rgenerator = new Random();
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
txt.setText(q);
}
}
};
}
Ignoring the MediaPlayer part, I think it should be this way:
package com.Randomsentence;
import java.util.Random;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.Randomsentence.R;
public class Randomsentence extends Activity {
TextView txt;
int random;
public String[] myStrings;
Button bt1;
private static final int MESSAGE_RANDOM = 1;
private static final long MIN_INTERVAL = 500;
private static final long MAX_INTERVAL = 1500;
private static final long STEP = 60;
private long mInterval = 0;
private boolean mStarted = false;
private Random mRandom = new Random();
private Handler mHandler = new Handler() {
#Override
public void handleMessage (Message msg) {
if(msg.what == MESSAGE_RANDOM) {
showRandomString();
if(mStarted) {
this.sendEmptyMessageDelayed(MESSAGE_RANDOM, mInterval);
} else {
if(mInterval <= MAX_INTERVAL) {
this.sendEmptyMessageDelayed(MESSAGE_RANDOM, mInterval);
mInterval += STEP;
} else {
this.removeMessages(MESSAGE_RANDOM);
Toast.makeText(Randomsentence.this, "Stopped!", Toast.LENGTH_SHORT).show();
}
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (TextView) findViewById(R.id.txt);
bt1 = (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(mBt1OnClick);
myStrings = getResources().getStringArray(R.array.myArray);
}
private void showRandomString() {
final int index = mRandom.nextInt(myStrings.length - 1);
txt.setText(myStrings[index]);
}
private OnClickListener mBt1OnClick = new OnClickListener() {
#Override
public void onClick(View v) {
if(!mStarted) {
// Start
Toast.makeText(Randomsentence.this, "Started!", Toast.LENGTH_SHORT).show();
mStarted = true;
mInterval = MIN_INTERVAL;
mHandler.removeMessages(MESSAGE_RANDOM);
mHandler.sendEmptyMessage(MESSAGE_RANDOM);
} else {
// Stop
mStarted = false;
Toast.makeText(Randomsentence.this, "Stoping...", Toast.LENGTH_SHORT).show();
}
}
};
}

Categories