I made two timers. At some point one of them is increasing and other one is decreasing. I made two integers to increase/decrease every second and use setText for TextView. But for some reason it's not updating. I printed out integers and code was working but text isn't changing for TextView. Here's my code:
TextView timerone, timertwo;
int turn = 1;
int timerOne = 20;
int timerTwo = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begin_after);
timerone = findViewById(R.id.timerone);
timertwo = findViewById(R.id.timertwo);
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
Thread counterThread=new Thread(()->{
try{
while(true){
if(turn % 2 == 0) {
timerOne++;
timerTwo--;
}else{
timerOne--;
timerTwo++;
}
Thread.sleep(1000);
}
}catch (Exception e){
}
});
counterThread.start();
}
If you want to modify views from off the UI thread, you need to use runOnUiThread or you will get an error. The following works to update the text views inside the loop.
TextView timerone = findViewById(R.id.timerone);
TextView timertwo = findViewById(R.id.timertwo);
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
Thread counterThread=new Thread(()->{
try{
while(true){
if(turn % 2 == 0) {
timerOne++;
timerTwo--;
}else{
timerOne--;
timerTwo++;
}
runOnUiThread(() -> {
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
});
Thread.sleep(1000);
}
}catch (Exception e){
}
});
counterThread.start();
Note, if your version of Java doesn't support lambdas, you can use this instead
runOnUiThread(new Runnable() {
#Override
public void run() {
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
}
});
Try this solution
Thread counterThread=new Thread(()->{
try{
while(true){
if(turn % 2 == 0) {
timerOne++;
timerTwo--;
}else{
timerOne--;
timerTwo++;
}
// Here you will be updating textview's
runOnUiThread(new Runnable() {
#Override
public void run() {
timerone.setText(String.valueOf(timerOne));
timertwo.setText(String.valueOf(timerTwo));
}
});
Thread.sleep(1000);
}
}catch (Exception e){
}
});
counterThread.start();
Related
I have two text fields that I want to show counting up and stopping at a certain number. Typically it works fine, but sometimes one or both stop short by one number.
final TextView t1 = (TextView) findViewById(R.id.text1);
final TextView t2 = (TextView) findViewById(R.id.text2);
winthread = new Thread(new Runnable() {
float store_count = oldstore;
int counter = 0;
public void run() {
while (counter < final_value) {
try {
Thread.sleep(100);
} catch (InterruptedException e) { }
t1.post(new Runnable() {
public void run() {
t1.setText(String.format("T1 $%.2f", store_count));
}
});
t2.post(new Runnable() {
public void run() {
t2.setText(String.format("T2 %d", counter));
}
});
counter++;
store_count = oldstore + counter * 5;
}
}
});
winthread.start();
From the code, T1 should stop at oldstore+final_valuex5 and T2 should stop at final_value but sometimes T1 stops at oldstore+final_valuex5-1 or T2 stops at final_value-1
The problem is that the method runs only after I press button second time, but the goal is to work for both methods one after another when I press button for the first time.
The first method is runThreadWork(); and after that runThreadRest(); when the first is completed.
This is the part for the button.
btnStartTimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(workMinutes > 0 || workSeconds > 0){
runThreadWork();
}else if(isTimerCompleted){
runThreadRest();
}
}
});
That's is the part for the method, basically both methods are the same in logic, but only change are variables for values, except TextView variable isn't changed for both methods, I want to use one TextView to show the output from both methods one after another.
private void runThreadWork() {
new Thread() {
public void run() {
while (workMinutes > 0 || workSeconds > 0) {
while (workSeconds > 0) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
workSeconds--;
String timeFormatedCountDownWork = String.format("Work time: " + "%02d:%02d", workMinutes, workSeconds);
txtTimeCountDown.setText(timeFormatedCountDownWork);
if(workSeconds == 0 && workMinutes > 0){
workMinutes--;
workSeconds = 60;
}
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}.start();
isTimerCompleted = true;
}
This question already has answers here:
Accessing views from other thread (Android)
(5 answers)
Closed 4 years ago.
in a tuner application on which I am working right now, I wanted to implement an Indicator which shows if the right pitch is played. For this I have implemented that the color of the indicator only changes when I hold the pitch for atleast 2 seconds.
public void thr(final double v1, final double v2) {
new Thread() {
#Override
public void run() {
super.run();
int i = 0;
while (pitchInHz >= v1 && pitchInHz < v2) {
if(i == 20){ //2 Sekunden
imageView.setBackgroundColor(getResources().getColor(holo_green_light));
}else {
imageView.setBackgroundColor(getResources().getColor(darker_gray));
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
}
running = false;
}
}.start();
Everytime my application tries to use the thread, the app just crashes.
some ideas why this is happening?
if(pitchInHz >= 72.41 && pitchInHz < 92.41) {
//e
noteText.setText("e"); //this is working
if(!running) {
thr(72.41, 92.41);
running = true;
}
I'm supposing it's because you're trying to access a view from a different thread than the main thread, which you cannot do such thing.
Try running like this:
public void thr(final double v1, final double v2) {
new Thread() {
#Override
public void run() {
super.run();
int i = 0;
while (pitchInHz >= v1 && pitchInHz < v2) {
if(i == 20){ //2 Sekunden
runOnUiThread(new Runnable() {
#override
public void run() {
imageView.setBackgroundColor(getResources().getColor(holo_green_light));
}
})
}else {
runOnUiThread(new Runnable() {
#override
public void run() {
imageView.setBackgroundColor(getResources().getColor(darker_gray));
}
})
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
}
running = false;
}
}.start();
Im a beginner android developer, so bear with me:
Im getting this error: "CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views"
Anyways, i have a media player with two threads, the first one updates a circular progress bar and the second one updates a text view that i want to use to show the time in the mp3 file. The first thread gives me no errors and runs perfectly fine. (I implemented this before the textview update)
The second thread however gives me the error in the title. I've looked into handlers asynctasks and runonuithread but I can't figure out how to utilize any of them since im using a while loop that's constantly updating it.
Also, why is only the second one giving me an error?
new Thread(new Runnable() {
#Override
public void run() {
ProgressBar myProgress = (ProgressBar) findViewById(R.id.circle_progress_bar);
int currentPosition = 0;
int total = mediaPlayer.getDuration();
myProgress.setMax(total);
while (mediaPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
myProgress.setProgress(currentPosition);
}
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
TextView currentTime = (TextView) findViewById(R.id.textView9);
int currentPosition = 0;
int total = mediaPlayer.getDuration();
while (mediaPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
currentTime.setText(getTimeString(currentPosition));
}
}
}).start();
And here's the code for getTimeString:
private String getTimeString(long millis) {
StringBuffer buf = new StringBuffer();
int hours = (int) (millis / (1000*60*60));
int minutes = (int) (( millis % (1000*60*60) ) / (1000*60));
int seconds = (int) (( ( millis % (1000*60*60) ) % (1000*60) ) / 1000);
buf
.append(String.format("%02d", hours))
.append(":")
.append(String.format("%02d", minutes))
.append(":")
.append(String.format("%02d", seconds));
return buf.toString();
}
do
myProgress.setMax(total);
in
runOnUIThread(new Runnable () {
#Override
public void run () {
myProgress.setMax(total);
}
});
Explanation
Views in android are only work/change/created on UI threads only. Other worker thread donot modify UI elements in Android, because Android is single threaded application.
You can also use AsyncTask which have onPreExecute() and onPostExecute() methods which run on UI thread to post updates to UI
As ρяσѕρєя K say, you can't update view in non-ui thread(Main Thread), so you can use a handler to finish this work
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO : change currentTime and myProgress as a class number //
TextView currentTime = (TextView) findViewById(R.id.textView9);
ProgressBar myProgress = (ProgressBar) findViewById(R.id.circle_progress_bar);
if (msg.what == 0) {
currentTime.setText(getTimeString(msg.arg1));
} else if (msg.what == 1) {
myProgress.setProgress(msg.arg1);
}
}
};
Then in you two thread, replace
// myProgress.setProgress(currentPosition);
handler.obtainMessage(1, currentPosition, 0).sendToTarget();
// currentTime.setText(getTimeString(currentPosition));
// param1 -> msg.what, param2 -> msg.arg1, parm3 -> msg.arg2
handler.obtainMessage(0, currentPosition, 0).sendToTarget();
Do you Ui work in run On Ui thread :
example:
new Thread(new Runnable() {
#Override
public void run() {
int currentPosition = 0;
int total = mediaPlayer.getDuration();
while (mediaPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
runOnUIThread(new Runnable () {
#Override
public void run () {
ProgressBar myProgress = (ProgressBar) findViewById(R.id.circle_progress_bar);
myProgress.setMax(total);
myProgress.setProgress(currentPosition);
}
});
}
}
}).start();
I have encountered a problem in my Android application. I need to create a switch so I can put multiple messages in a handler instead of creating a million handlers. Here is my code:
String text1 = spinner1.getSelectedItem().toString().trim();
String text2 = spinner2.getSelectedItem().toString().trim();
dialog1 = ProgressDialog.show(getActivity(), "", "Calculating...");
if (text1.equals("US Dollar - USD") && text2.equals("Euro - EUR") && edittextdollars.length() > 0 && edittexteuros.length()==0) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try{
handler.sendEmptyMessage(0);
convertvalues("USD", "EUR");
}
catch (Exception e) {
}
}
});
thread.start();
}
public Handler handler = new Handler () {
public void handleMessage(android.os.Message msg) {
dialog1.dismiss();
convertvalues("USD", "EUR");
}
}
;
This works, but I want to create more messages for multiple if statements, like this:
if (text1.equals("US Dollar - USD") && text2.equals("Euro - EUR") && edittextdollars.length() > 0 && edittexteuros.length()==0) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try{
handler.sendEmptyMessage(0);
convertvalues("USD", "EUR");
}
catch (Exception e) {
}
}
});
thread.start();
}
if (text1.equals("US Dollar - USD") && text2.equals("Euro - EUR") && edittexteuros.length() > 0 && edittextdollars.length()==0) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try{
handler.sendEmptyMessage(0);
convertvalues2("EUR","USD");
}
catch (Exception e) {
}
}
});
thread.start();
}
if (text1.equals("Euro - EUR") && text2.equals("US Dollar - USD") && edittextdollars.length() > 0 && edittexteuros.length()==0) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try{
handler.sendEmptyMessage(0);
convertvalues("EUR","USD");
}
catch (Exception e) {
}
}
});
thread.start();
}
How do I achieve this? Is it with a switch, or something else. Any help is greatly appreciated.
P.S.
Since I am a beginner, it would be great if you post code also with your answer. That would be great. And once again, thank you.
Switch statements in java work with ints and enums and a few other types.
So in your case, you might want to setup an enum to hold the possible values that you might want to switch on.
public enum Currency{
USD,
EUR
}
private void test(Currency currency){
switch (currency){
case USD:
doUsdStuff();
break;
case EUR:
doEurStuff();
break;
}
}
Alternatively, you could declare int values instead of enums.
Since you have two values, you might do two switch statements, saving the value of each then do one call to convertValues() with the saved values.
You would use variables instead. Try to extract the things that change, and build the code around that. In your case the call to convertvalues2 varies, so extract the arguments to variables and use those.
final String fromCurrency = text1.substring(text1.length() - 3);
final String toCurrency = text2.substring(text2.length() - 3);
new Thread(new Runnable() {
#Override
public void run() {
try{
handler.sendEmptyMessage(0);
convertvalues2(fromCurrency, toCurrency);
}
catch (Exception e) {
}
}
});